【问题标题】:How to marshall array of structs in C#?如何在 C# 中编组结构数组?
【发布时间】:2009-04-08 11:09:10
【问题描述】:

我在 C# 中有以下结构:

[StructLayoutAttribute(LayoutKind.Sequential)]
public struct RECORD
{
    public uint m1;
    public uint m2;
    public uint m3;
}

我还需要将这些结构的数组(固定长度)传递给本机代码,它会将一些数据写入这些结构。该数组在 C# 中分配并传递给 C dll。我将导入的函数声明为:

[DllImport("marshall.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern void doIt(RECORD[] dataRecord);

但我没有得到任何数据。我已经尝试过 PInvoke Interop Assistant。我应该在这里使用 IntPtr 吗?有什么想法吗?

编辑:

这是调用本机函数的 C# 代码:

RECORD[] rec = new RECORD[256];
doIt(rec);
// values of rec are all zero here

这里是 C 函数:

int doIt(RECORD* rec)
{
    // deref pointer and write some data
}

【问题讨论】:

    标签: c# marshalling


    【解决方案1】:

    我远非 P/Invoke 专家,但我想知道将其设为输入/输出参数是否会有所帮助:

    DllImport("marshall.dll", CallingConvention = CallingConvention.Cdecl)]
    private static extern void doIt([In, Out] RECORD[] dataRecord);
    

    我不会预期这是必要的,就像LayoutKind.Sequential 一样,我希望你的结构已经是一个 blittable 类型,并且数组也是 blittable。

    【讨论】:

    • 成功了,谢谢。还有其他地方使用这些关键字吗?我以前从未见过他们
    • 来自 MSDN:[指 blittable 类型的数组] 但是,这些类型实际上是作为 In 参数编组的,如果要将参数编组为 In/,则必须应用 InAttribute 和 OutAttribute 属性输出参数。
    • 感谢这对我有用 - 并结束了两个小时的努力来完成这项工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多