在pInvoke中编组一组结构

时间:2013-11-27 12:47:35

标签: c# c++ arrays pinvoke marshalling

我在C#中有这样的结构:

[StructLayout(LayoutKind.Sequential, Pack = 8)]
public struct MyStruct
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 17)]
    public string StringValue;
    public uint IUintValue;
}

本机代码中的相应结构

struct MyStruct
{
    char StringValue[17];
    ulong UintValue;
}

我的目标是使用pinvoke将此结构的数组从c#侧传递到c ++(本机端)。 以下是我在c#

中使用它的方法
[DllImport(@"MyLibrary.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl)]
public static extern int SendArray([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)]ref MyStruct[] arr, int recordsCount);

并且调用代码是:

var array = new MyStruct[10];
//initialize
SendArray(ref array, array.Length);

在原生方面,我有以下功能签名:

extern "C" __declspec(dllexport) int SendArray(MyStruct** Arr, int recordsCount);

它似乎只适用于数组中的第一个元素。在c ++方面,我得到了这个数组,但只有第一个元素被正确编组。其余的似乎是垃圾。

我的错误在哪里?

1 个答案:

答案 0 :(得分:3)

您的C ++代码未收到结构数组。它接收一个指向struct的指针数组。将C ++代码更改为:

int SendArray(MyStruct* Arr, int recordsCount);

或者

int SendArray(MyStruct Arr[], int recordsCount);

然后你的p / invoke应该是

[DllImport(...)]
public static extern int SendArray([In] MyStruct[] arr, int recordsCount);

我也怀疑Pack=8。你确定吗?

相关问题