Marshaling information can be set with the Reflection Emit classes in the Runtime class library. Two class in particular allow marshaling information for parameters and fields to be supplied. Both ParameterBuilder and FieldBuilder have a SetMarshal method.
public class ParameterBuilder { … public virtual void SetMarshal(NativeMarshal nativemarshal); } public class FieldBuilder: FieldInfo: FieldInfo { … public virtual void SetMarshal(NativeMarshal nativemarshal); }
Both SetMarshal methods take a NativeMarshal object as their only argument. Calling the one of the static methods on the NativeMarshal class creates the native marshal object. The DefineNativeMarshal method is used for most simple unmanaged types. DefineByValStr is used for fixed length string buffer. DefineSafeArray is used for COM SafeArrays.
public class NativeMarshal { // used to define all type except those listed below static NativeMarshal DefineNativeMarshal(UT t); // used to define a fixed length string buffer within a class. The elemCount argument identifies the size of the buffer. The Type of characters within the unmanaged buffer is determined by the charset of the class. This type can only be used on fields. It is not permitted on parameters. static NativeMarshal DefineByValTStr(int elemCount) // used to define a COM SafeArray. The elemType argument is optional. It is only needed when the array elements are string types. This type can only be used on Parameters static NativeMarshal DefineSafeArray([optional] UT elemType) // used to define a fixed length array field within a class. The elemCount argument identifies the number of elements within the array The elemType argument is optionally used to identify the type of the elements within the array. It is only necessary for elements that are string types. This type can only be used on fields. It is not permitted on parameters. static NativeMarshal DefineByValArray(int elemCount); // used to define a variable length array being used as a parameter. The elemType argument is optionally used to identify the type of the elements within the array. It is only necessary for elements that are string types. This type can only be used on parameters. It is not permitted on fields. static NativeMarshal DefineLPArray(UT elemType); // used to define a custom marshaler. The MarshalProvider argument identifies the type that will server as the marshal provider. This type must implement ICustomMarshal. The IID argument is identifies the COM type that the marshal provider will convert this parameter to. The cookie optionally used to pass data to the marshal provider when it is constructed. See the Attributed Marshaling spec for more details. static NativeMarshal DefineCustomMarshaler(Type MarshalerProvider, String IID; String Cookie) }