指向具有另一个结构的固定数组的结构的指针

时间:2016-08-05 20:24:17

标签: c# pinvoke marshalling

我正在尝试为本机DLL编写C#绑定。在DLL中的结构定义为

typedef struct Foo {
    Bar bars[32];
} Foo;

typedef struct Bar {
    uint32_t data;
} Bar;

和一个功能

void Baz(Foo* foo);

理想情况下,我想将C#结构定义为

public unsafe struct Foo {
    public unsafe fixed Bar bars[32]
}

public struct Bar {
    public uint data;
}

和函数

public unsafe void BazDelegate(Foo* foo);

这将允许我使用指针来操纵结构。但是,这是不允许的,因为固定数组只能用于基本类型,所以我不能拥有第二种类型的固定数组。 API要求第一种类型通过指针传递给某个函数。

我发现的唯一解决方案是将字段类型更改为托管数组Bar[],并让编组人员处理它。但那意味着我可以'拿一个结构的指针。所以我必须将函数的签名从不安全的指针更改为ref

不使用[DllImport]编写绑定。它们在运行时通过Marshal.GetDelegateForFunctionPointer加载。我可以更改结构使用[MarshalAs(UnmanagedType.ByValArray)],函数使用ref Foo代替Foo*吗?

使用从Marshal.GetDelegateForFunctionPointer考虑P / Invoke创建的函数吗?如果托管数组未通过[DllImport],它们仍会被编组吗?如果ref传递,他们会被编组吗?

0 个答案:

没有答案
相关问题