【问题标题】:C# pointer to unmanaged struct with arrayC# 指向带有数组的非托管结构的指针
【发布时间】:2013-07-06 09:45:44
【问题描述】:

我正在尝试在 C# 中实现 C 风格的结构以实现互操作性。

这是我要转换的结构:

typedef struct
{
    UINT8  TrafficClass0:4;
    UINT8  Version:4;
    UINT8  FlowLabel0:4;
    UINT8  TrafficClass1:4;
    UINT16 FlowLabel1;
    UINT16 Length;
    UINT8  NextHdr;
    UINT8  HopLimit;
    UINT32 SrcAddr[4];
    UINT32 DstAddr[4];
} DIVERT_IPV6HDR, *PDIVERT_IPV6HDR;

这是我的 C# 结构:

[StructLayoutAttribute(LayoutKind.Sequential)]
public struct DivertIPv6Header
{
    /// TrafficClass0 : 4
    /// Version : 4
    /// FlowLabel0 : 4
    /// TrafficClass1 : 4
    public uint bitvector1;

    /// UINT16->unsigned short
    public ushort FlowLabel1;

    /// UINT16->unsigned short
    public ushort Length;

    /// UINT8->unsigned char
    public byte NextHdr;

    /// UINT8->unsigned char
    public byte HopLimit;

    /// UINT32[4]
    [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4, ArraySubType = UnmanagedType.U4)]
    public uint[] SrcAddr;

    /// UINT32[4]
    [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4, ArraySubType = UnmanagedType.U4)]
    public uint[] DstAddr;

    public uint TrafficClass0
    {
        get
        {
            return bitvector1 & 15u;
        }
        set
        {
            bitvector1 = value | bitvector1;
        }
    }

    public uint Version
    {
        get
        {
            return (bitvector1 & 240u) / 16;
        }
        set
        {
            bitvector1 = (value * 16) | bitvector1;
        }
    }

    public uint FlowLabel0
    {
        get
        {
            return (bitvector1 & 3840u) / 256;
        }
        set
        {
            bitvector1 = (value * 256) | bitvector1;
        }
    }

    public uint TrafficClass1
    {
        get
        {
            return (bitvector1 & 61440u) / 4096;
        }
        set
        {
            bitvector1 = (value * 4096) | bitvector1;
        }
    }
}

这里唯一的问题是我需要声明一个指向这个结构的指针,以便我可以与它的数据重叠。

如果我尝试声明一个指针,我得到了这个编译时错误:

cannot declare pointer to non-unmanaged type.

有什么想法吗?

【问题讨论】:

  • 您不太可能需要指针,但您没有提供足够的信息。 “重叠”表明您实际上想要声明一个联合,您可以使用 [StructLayout(LayoutKind.Explicit)] 属性来执行此操作。但这仍然是数组成员的问题,出于同样的原因,您不能声明指向此结构的指针,您需要使用 fixed 关键字将它们声明为固定大小的缓冲区。
  • 我对工会不感兴趣。我有一个指向 byte* 数组的指针,我想将它转换为 DivertIPv6Header*。
  • 这是 Marshal.PtrToStructure(),不使用 fixed 也能正常工作。您对您的要求如此含糊,并没有帮助我们帮助您。
  • 你有一个指向字节指针数组的指针吗?

标签: c# pointers data-structures interop unmanaged


【解决方案1】:

使用Marshal.PtrToStructure:

        var bytes = yourUnmanagedByteArray;

        fixed (byte* b = bytes)
            return (T)Marshal.PtrToStructure(new IntPtr(b), typeof(DivertIPv6Header));

如果您不想使用 unsafe 代码,也可以在没有 fixed 缓冲区的情况下使其工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多