Share via


Implementing the ICustomMarshaler Interface

To use a custom marshaler, you must apply the MarshalAsAttribute attribute to the parameter or field being marshaled. The attribute identifies the custom marshaler that activates the appropriate wrapper.

The custom marshaler implements the ICustomMarshaler Interface interface to provide the appropriate wrappers to the runtime, creating the custom marshaler the first time an argument needs to be marshaled. It calls the MarshalNativeToManaged and MarshalManagedToNative methods on the custom marshaler to activate the correct wrapper to handle the call. The following table describes each method exposed by the ICustomMarshaler interface.

Interface method Description
MarshalNativeToManaged Returns a custom runtime callable wrapper that can marshal the unmanaged interface passed as an argument. The marshaler should return an instance of the custom runtime callable wrapper for that type.
MarshalManagedToNative Returns a custom COM callable wrapper that can marshal the managed interface passed as an argument. The marshaler should return an instance of the custom COM callable wrapper for that type.
CleanUpNativeData Provides an opportunity for the custom marshaler to perform any necessary cleanup of the wrapper returned by the MarshalManagedToNative method.
CleanUpManagedData Provides an opportunity for the custom marshaler to perform any necessary cleanup of the wrapper returned by the MarshalNativeToManaged method.
GetInstance Retrieves an instance of the custom marshaler. This static method can either create a new instance of the custom marshaler every time or it can always use the same one if the custom marshaler is stateless. The method is called by the marshaling service to create the marshaler whenever a parameter or field is marked with the UnmanagedType.CustomMarshaler.

See Also

Custom Marshaling | Defining the Marshaling Type | Using a Substitute Marshaler