我在 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++( native 端)。 这是我在 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);
在 native 端,我有以下函数签名:
extern "C" __declspec(dllexport) int SendArray(MyStruct** Arr, int recordsCount);
而且它似乎只对数组中的第一个元素有效。在 C++ 方面,我得到了这个数组,但只有第一个元素被正确编码(marshal)。其余的似乎是垃圾。
我的错误在哪里?
最佳答案
您的 C++ 代码不接收结构数组。它接收指向结构的指针数组。将 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
。你确定吗?
关于c# - 在 pInvoke 中编码结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20242950/