c# - 使用结构 union 将 C++ 编码到 C# 结构

标签 c# c++ com interop marshalling

我不是 COM 或 C++/C# 编码(marshal)处理方面的专家,在这种情况下需要一些帮助:

native 代码:

typedef struct _Foo {
    FooType a; // enum
    WCHAR b[16];
    WCHAR c[16];
    BOOL d;
    ULONG size;
} Foo;

typedef struct _Bar {
    GUID a;
    WCHAR b[16];
    WCHAR c[16];
    BOOL d;
} Bar;

typedef struct _Baz {
    FILETIME a;
    FILETIME b;
    ULONG c;
    ULONG d;
    GUID e;
} Baz;

typedef struct _FooBarBaz
{
    SomeType type; // enum

    [switch_is(type)] union
    {
        [case(SomeType.A)]
        Foo a;

        [case(SomeType.B)]
        Bar b;

        [case(SomeType.C)]
        Baz b;
    } data;
} FooBarBaz;

托管代码:

[StructLayout(LayoutKind.Sequential)]
internal struct Foo
{
    public FooType a;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
    public char[] b;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
    public char[] c;

    [MarshalAs(UnmanagedType.Bool)]
    public bool d;

    [MarshalAs(UnmanagedType.U4)]
    public uint e;
}

[StructLayout(LayoutKind.Sequential)]
internal struct Bar
{
    public Guid a;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
    public char[] b;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
    public char[] c;

    [MarshalAs(UnmanagedType.Bool)]
    public bool d;
}

[StructLayout(LayoutKind.Sequential)]
internal struct Baz
{
    public ComTypes.FILETIME a;

    public ComTypes.FILETIME b;

    [MarshalAs(UnmanagedType.U4)]
    public uint c;

    [MarshalAs(UnmanagedType.U4)]
    public uint d;

    public Guid e;
}

internal struct FooBarBaz
{
    public SomeType Type;

    // ??????
}

我不确定如何将 native 结构 FooBarBaz 转换/编码为托管代码。如有任何提示,我们将不胜感激。

最佳答案

关于翻译的宝贵资源可以找到here IMO,每一页都值得阅读 :)

关于FooBarZ,你要找的是[FieldOffset(NBR)],就是翻译union的方式。

the translation in pinvokeSTRRET struct有关如何使用它的示例。

关于c# - 使用结构 union 将 C++ 编码到 C# 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17737088/

相关文章:

c++ - 如何推断仿函数返回值的类型?

windows - 如何从 COM 服务器调用释放

c++ - 深奥的 JScript 托管问题:IDispatch::Invoke 返回 SCRIPT_E_PROPAGATE 时的错误代码在哪里?

c# - LINQ - 加入 Group By 并获得平均值

c++ - 继承和覆盖 std::string 的函数?

c# - 在属性更改时触发 ListViewItem 行为?

c++ - 改进模板类中的编译时错误消息

vba - 无法在 VBA 中使用我的简单 VB 类库

c# - Javascript JSON仅序列化第一级

c# - <typeparamref> 到 C# XML 文档中另一个类的参数