具有未指定长度数组的PInvoke结构

时间:2013-03-24 23:38:30

标签: c# pinvoke

C定义

typedef struct {
    const uint8_t* buf;
    int bufLen;
} Info;


int Foo(Info* info);

C#定义

[StructLayout(LayoutKind.Sequential)]
public struct Info
{
     // [MarshalAs( ??? )]
     public byte[] buf;
     int bufLen
}    

[DllImport(...)]
public static extern int Foo(ref Info info);

我无法确定在C#struct定义中为MarshalAs上的byte[] buf属性指定的内容。缓冲区在.NET端分配,其长度在调用时已知。

在一个简单的小测试中:

var info = new Info {
    buf = new byte[] {0x40, 0x50, 0x60, 0x70},
    bufLen = 4,
};

Foo(ref info);

一切似乎都正常工作,但事实上我的缓冲区中的数据不正确。从DLL打印我看到01 00 80 00 - 不确定是什么。

我试过了:

  • MarshalAs
  • [MarshalAs(UnmanagedType.SafeArray)]

没有任何作用。

一般来说,我真的不知道调试这类问题的最佳方法。

2 个答案:

答案 0 :(得分:3)

根据Hans Passant的建议,我实施了以下内容:

[StructLayout(LayoutKind.Sequential)]
public struct Info : IDisposable
{
    private IntPtr buf;
    private int bufLen;

    public Info(byte[] buf) : this() {
        this.buf = Marshal.AllocHGlobal(buf.Length);
        Marshal.Copy(buf, 0, this.buf, buf.Length);
        this.bufLen = buf.Length;
    }

    public void Dispose() {
        if (buf != IntPtr.Zero) {
            Marshal.FreeHGlobal(buf);
            buf= IntPtr.Zero;
        }
    }
}

答案 1 :(得分:0)

我知道为时已晚......但是如果有人来这里寻求答案的话。

我终于想出了类似练习的下一个解决方案。

[StructLayout(LayoutKind.Sequential)]
public struct Info
{
     [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
     public byte[] buf;
     int bufLen
}

来自MSDN

  

数组可以编组为UnmanagedType.ByValArray,其中   要求您设置MarshalAsAttribute.SizeConst字段。尺寸   只能设为常数。

在我的情况下,缓冲区大小为8个字节。

相关问题