none
Can I emit a Custom Marshaller on a class field? RRS feed

  • Question

  • I've created my custom marshaller and successfully tested by attaching it to a P/Invoke native call parameter like so:

        [DllImport( SIMPLE_TEST_DLL, CallingConventionCallingConvention = CallingConvention.Winapi, SetLastError = trueCharSetCharSet = CharSet.Auto )]  
        internal static unsafe extern UInt32 EvenSimplerCall(  
            [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( MyCustomTypeMarshaller ) )]  
            MyType foo  
        ); 

    This works great. However, I'd like to send that custom marshallable parameter inside of an encapsulating structure, so I attached the custom marshaller to a class field instead:

        class OuterType  
        {  
            [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( MyCustomTypeMarshaller ) )]  
            public MyType foo;  
        }  
     
     
        [DllImport( SIMPLE_TEST_DLL, CallingConventionCallingConvention = CallingConvention.Winapi, SetLastError = trueCharSetCharSet = CharSet.Auto )]  
            internal static unsafe extern UInt32 DifferentCall(  
            OuterType bar  
        );  
     

    But now the CLR doesn't seem to call in to the custom marshaller. The native side gets a bad pointer. Shouldn't the CLR know to marshal MyType foo using MyCustomMarshaller?

    Saturday, December 6, 2008 1:39 AM

Answers

  • Custom marshallers only work on method arguments, not fields.  You can implement custom marshaling on fields simply by declaring the field member as an IntPtr and perform the marshaling before and/or after the method call.
    Hans Passant.
    • Marked as answer by Zhi-Xin Ye Thursday, December 11, 2008 1:20 PM
    Saturday, December 6, 2008 4:38 PM
    Moderator