【问题标题】:How to call external method with struct parameter that contains union [duplicate]如何使用包含联合的结构参数调用外部方法[重复]
【发布时间】:2016-09-26 07:35:04
【问题描述】:

C++ 代码是:

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;

而我的 C# 代码是:

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);

如何正确地将 union 转换为 C# 代码?当我调用 ExecuteCommand 时,我收到的回复应该包含肯定或否定回复(C++ 方法也是如此)。

【问题讨论】:

  • 从 c# 的角度来看,您正在传递一个包含 REPLY_TYPE 的结构。所有 c# 关心的是对象的大小。在 c 语言中,union 是一个可以包含多个项目的定义,但它实际上只是存储在内存中的单个项目。

标签: c# c++ marshalling


【解决方案1】:

您不能在 C# 中复制 C 联合。您应该这样做(根据您的真实代码更改类型名称和常量):

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; } } }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-31
    • 2014-09-07
    • 2018-11-12
    • 2020-10-14
    • 1970-01-01
    相关资源
    最近更新 更多