c# - 将 C++ 结构体 union 转换为 C#

标签 c# c++ struct pinvoke unions

我正在尝试使用 C# 来使用 C++ 库,该库包含一个记录为如下布局的结构:

struct {
    long outervar;
    long othervar;
    union {
        struct {
            long a;
        } firststruct;
        struct {
            long p;
            long q;
            long r;
            long s;
        } secondstruct;
        struct {
            long x;
            long y;
            long z;
        } thirdstruct;
    } myunion;
} outerstruct;

理想情况下我想实现这样的东西:

struct outerstruct
{
    UInt32 outervar;
    UInt32 othervar;
    [FieldOffset(0)]
    struct firststruct
    {
        UInt32 a;
    }
    [FieldOffset(0)]
    struct secondstruct
    {
        UInt32 p;
        UInt32 q;
        UInt32 r;
        UInt32 s;   
    }
    [FieldOffset(0)]
    struct thirdstruct
    {
        UInt32 x;
        UInt32 y;
        UInt32 z;
    }
}

当然,我不能在结构上使用 FieldOffset 或 MarshalAs,但我不知道如何实现它。如果有人对如何在 C# 中实现这一点有一些想法,我将不胜感激。

谢谢!

最佳答案

[FieldOffset] 在结构字段上很好。但是您的声明只有嵌套类型(请注意,在 C++ 代码中,结构实际上是匿名的,但用于声明新字段...您的 C# 代码仅声明一个命名 结构,但没有实际的 field )。请注意,您还需要包含 [StructLayout(LayoutKind.Explicit)],并为结构中的所有字段提供偏移量。

尝试这样的事情:

struct firststruct
{
    UInt32 a;
}

struct secondstruct
{
    UInt32 p;
    UInt32 q;
    UInt32 r;
    UInt32 s;
}

struct thirdstruct
{
    UInt32 x;
    UInt32 y;
    UInt32 z;
}

[StructLayout(LayoutKind.Explicit)]
struct union
{
    [FieldOffset(0)]
    firststruct firststruct;
    [FieldOffset(0)]
    secondstruct secondstruct;
    [FieldOffset(0)]
    thirdstruct thirdstruct;
}

struct outerstruct
{
    UInt32 outervar;
    UInt32 othervar;
    union union;
}

关于c# - 将 C++ 结构体 union 转换为 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26390414/

相关文章:

c - C 混淆中的结构

c# - 在包含两个位集的 C++ 结构上使用 C# 的 Marshal.PtrToStructure

c++ - 为什么 std::vector::operator[] 比 std::vector::at() 快 5 到 10 倍?

c++ - 将行拆分为整数

c - 在结构中分配动态数组

c - 返回结构

c# - PowerPoint.Application 未在 C# 中引发事件

c# - 以不同用户身份启动 .Net 进程

c# - 在 C# 中将科学计数法字符串转换为 float

c++ - 将参数正确传递给使用 Qt 的 QProcess 运行的 Linux 二进制文件