0

The C++ code is:

DLL_API DWORD WINAPI ExecuteCommand( LPCSTR, CONST COMMAND, CONST DWORD, LPREPLY);

typedef struct
{
    REPLY_TYPE      replyType;

    union
    {
        POSITIVE_REPLY  positiveReply;
        NEGATIVE_REPLY  negativeReply;
    }
    message;

}
REPLY;

And my C# code is:

public struct Reply
{
    public ReplyType ReplyType;

    public PositiveReply PositiveReply;
    public NegativeReply NegativeReply;
}

[DllImport(@"my.dll")]
public static extern int ExecuteCommand(string port, Command command, int timeout, ref Reply reply);

How can I properly transfer union to C# code? When I call ExecuteCommand I receive reply which should contain either Positive or Negative Reply (such does C++ method).

Anton23
  • 2,079
  • 5
  • 15
  • 28
  • Have a look at [FieldOffsetAttribute](https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.fieldoffsetattribute(v=vs.110).aspx) – Aleksey L. Sep 26 '16 at 07:39
  • From a c# perspective you are passing a structure that contains a REPLY_TYPE. All c# care about is the size of the object. In c language a union is a definition that can contain multiple items, but it is actually just a single item stored in memory. – jdweng Sep 26 '16 at 07:45

1 Answers1

0

You cannot replicate C union in C#. You should do something like this (change type names and constants according to your real code):

public struct Reply { public int rt; public object o; public int? pr { get { return rt == 1 ? (int?)o : null; } } public int? nr { get { return rt == 0 ? (int?)o : null; } } }

Peter Krassoi
  • 571
  • 3
  • 11