locked
interior_ptr and interop marshaling RRS feed

  • Question

  • I'm working on a project in which I sometimes use interior_ptr in combination with COM Interop. When calling COM components from .NET, this always works fine. However, recently I've encountered a strange problem calling .NET components from COM using interior_ptr. Maybe it's good to let the code do the talking:

     

    Code Snippet

    [ComVisible(true), StructLayout(LayoutKind::Sequential)]

    public value struct MyStruct

     {

      [MarshalAs(UnmanagedType::LPStr)]

      String^ lpszMyString;

     };

     

    [ComVisible(true), InterfaceType(ComInterfaceType::InterfaceIsIUnknown),

     Guid("some guid...")]

    public interface class IMyInterface1

     {

      void MyFunc1([In] interior_ptr<MyStruct> pMyStruct);

     };

     

    [ComVisible(true), InterfaceType(ComInterfaceType::InterfaceIsIUnknown),

     Guid("another guid...")]

    public interface class IMyInterface2

     {

      void MyFunc2([In] MyStruct^ pMyStruct);

     };

     

    [ComVisible(true), Guid("again another guid...")]

    public ref class MyDotNetClass : public IMyInterface1, IMyInterface2

     {

      public:

        virtual void MyFunc1(interior_ptr<MyStruct> pMyStruct)

         {

          Forms::MessageBox::Show("Inside MyFunc1");

         }

     

        virtual void MyFunc2(MyStruct^ pMyStruct)

         {

          Forms::MessageBox::Show("Inside MyFunc2");

         }

     };

      

    These are the results when calling MyDotNetClass from unmanaged code:

     

    MyInterface1->Func1(pStruct); /// OK

    MyInterface1->Func1(NULL); // Crash!!

    MyInterface2->Func2(pStruct); // OK

    MyInterface2->Func2(NULL); // OK!?

     

    The crash only occurs when the structure contains types that require special marshaling. It seems that the marshaler tries to marshal fields even when  the pointer to their containing structure is a nullptr. This only happens when passing as an interior_ptr and not when passing as a handle.

     

    Is there some explanation for this behaviour or is it just by design?

     

    Bert

    Monday, May 28, 2007 8:45 AM