0

Consider the following method from PInvoke.dll:

union MYUNION2
{
    int i;
    char str[128];
};
PINVOKELIB_API void TestUnion2( MYUNION2 u, int type )
{
    //...implementation is irrelevant...
}

According to MSDN:

In managed code, value types and reference types are not permitted to overlap. This sample uses method overloading to enable the caller to use both types when calling the same unmanaged function.

The managed code for the sample is as follows:

[StructLayout(LayoutKind.Explicit, Size=128)]
public struct MyUnion2_1
{
    [FieldOffset(0)]
    public int i;
}
[StructLayout(LayoutKind.Sequential)]
public struct MyUnion2_2
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)]
    public string str;
}
[DllImport( "..\\LIB\\PInvokeLib.dll")]
public static extern void TestUnion2(MyUnion2_1 u, int type);  

[DllImport( "..\\LIB\\PInvokeLib.dll")]
public static extern void TestUnion2(MyUnion2_2 u, int type);

That's all fine and dandy in P/Invoke, but how do I do that in COM Interop? Obviously I can't just create overloads as the CLR relies on the methods' exact position in the vtable. It's as if I need a COM-method equivalent of FieldOffsetAttribute.

Create two interfaces (one for each overload) works, but it's a little awkward...

Ohad Schneider
  • 36,600
  • 15
  • 168
  • 198
  • This requires violence. First directed at the dev to get him to fix this. Next the *fixed* keyword in C# so you can declare the union. Use Encoding.Default to convert the string by hand, don't forget to zero-terminate it. – Hans Passant Jun 04 '14 at 23:24
  • Well I'm the only developer so violence won't be a problem :) I can already see I'll like the two interfaces solution better, but out of curiosity I want to get your suggestion to work. I tried `[StructLayout(LayoutKind.Explicit)] public struct MyUnion { [FieldOffset(0)] public int i; [FieldOffset(0)] public fixed char str[128]; }` (in unsafe context of course) but even accessing the integer doesn't work (nothing happens when I call the method). – Ohad Schneider Jun 06 '14 at 07:26

0 Answers0