c# - 在 pInvoke 中编码结构数组

标签 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++( 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/

相关文章:

c# - 将 Action<T> 回调转换为等待

c# - Xamarin 表格 : Grouping ObservableCollection

c# - 我正在尝试在我的新类中使用 dll 导入,但出现错误属性 'DllImport' 在此声明类型上无效

c++ - 无锁单写多读者列表实现细节

c++ - 错误:当我继承 std::vector 时,预期 ‘)’ 在 ‘start’ 之前

c# - 系统内存不足异常大txt文件放入数组

c++ - 如何使用变量作为其大小来声明 char 数组?

c# - 模拟 HttpContext.Current.User.Identity.Name

c# - 无法将结构从 C++ 返回到 C#

java - 对象数组的问题