Unions in C# - incorrectly aligned or overlapped with a non-object field

后端 未结 2 690
旧巷少年郎
旧巷少年郎 2021-01-15 08:56

I am marshaling via PInvoke to a native C dll which expects the following call.

private static extern int externalMethod(IntPtr Data, [MarshalAs(UnmanagedTyp         


        
2条回答
  •  再見小時候
    2021-01-15 09:58

    Just use the A/B/C/D structs directly and skip the union. In your extern calls, simply substitute the correct struct in the method declaration.

    extern void UnionMethodExpectingA( A a );
    

    If the unmanaged methods actually accept a union and behave differently based on the type passed, then you can declare different extern methods that all end up calling the same unmanaged entry point.

    [DllImport( "unmanaged.dll", EntryPoint="ScaryMethod" )]
    extern void ScaryMethodExpectingA( A a );
    
    [DllImport( "unmanaged.dll", EntryPoint="ScaryMethod" )]
    extern void ScaryMethodExpectingB( B b );
    

    Updated for "length" parameter. The logic still applies. Just create a "wrapper" method and do the same thing.

    void CallScaryMethodExpectingA( A a )
    {
      ScaryMethodExpectingA( a, Marshal.SizeOf( a ) );
    } 
    

提交回复
热议问题