Implementing the ICustomMarshaler Interface

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

The following C# code displays the base interface that must be implemented by all custom marshalers:

namespace System.Runtime.InteropServices
{
    using System;

[System.Runtime.InteropServices.ComVisible(true)]
    public interface ICustomMarshaler
    {
     Object MarshalNativeToManaged( IntPtr pNativeData );
     IntPtr MarshalManagedToNative( Object ManagedObj );
     void CleanUpNativeData( IntPtr pNativeData );
     void CleanUpManagedData( Object ManagedObj );
     int GetNativeDataSize();
    }
}

Your custom marshaler must implement the ICustomMarshaler interface to provide the appropriate wrappers to the runtime.

In addition, you must implement the following static method, which you can call to retrieve an instance of the custom marshaler:

static ICustomMarshaler *GetInstance(String *pstrCookie);

The runtime creates the custom marshaler the first time an argument has to be marshaled. The runtime then calls the ICustomMarshaler.MarshalNativeToManaged and ICustomMarshaler.MarshalManagedToNative methods on the custom marshaler to activate the correct wrapper to handle the call. The following table describes the methods exposed by the ICustomMarshaler interface.

Method

Description

MarshalNativeToManaged

Marshals a pointer to native data into a managed object. This method returns a custom runtime callable wrapper (RCW) that can marshal the unmanaged interface that is passed as an argument. The marshaler should return an instance of the custom RCW for that type.

MarshalManagedToNative

Marshals a managed object into a pointer to native data. This method returns a custom COM callable wrapper (CCW) that can marshal the managed interface that is passed as an argument. The marshaler should return an instance of the custom CCW for that type.

CleanUpNativeData

Enables the marshaler to clean up the native data that is returned by the MarshalManagedToNative method.

CleanUpManagedData

Enables the marshaler to clean up the managed data that is returned by the MarshalNativeToManaged method.

GetNativeDataSize

Returns the size of the unmanaged data to be marshaled.

See Also

Concepts

Defining the Marshaling Type

Using a Substitute Marshaler

Other Resources

Custom Marshaling