c# - 在 C# 中使用 C++ unsigned int *array

标签 c# c++ .net arrays dll

我有一个 c++ .dll 导出一个具有以下签名的函数:

extern int __stdcall foobar(long ptr, unsigned int *array, unsigned int arraySize);

从 C++ 代码,我可以像这样使用它:

std::vector<unsigned int> FooBar(6);
int res = foobar(ptr, &FooBar[0], (unsigned int)FooBar.size());

我想使用 C# 中的 dll,我试过这个:

[DllImport("mydll.dll")]
public static extern int foobar(long ptr, uint[] arr, uint arrSize);

调用:

uint[] arr = new uint[6];
int count = Obj.foobar(ptr, arr, (uint)arr.GetLength(0)*32)

这会引发“PInvokeStackImbalance”错误。正确的 PInvoke 签名应该是什么样的?

最佳答案

您将需要使用 MarshalAs属性,用于您的数组参数。这实质上向编码系统描述了如何在 C# 托管类型和原始 C++ 函数参数之间进行转换。

[DllImport("mydll.dll")]
public static extern int foobar(
    IntPtr ptr, //Need more details on this parameter
    [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=2)] uint[] arr,
    uint arrSize);

您的“ptr”参数有点令人困惑,因为您的问题中没有提到它,但它很可能只是您可以将其视为常规旧 C++ 指针的东西,在这种情况下,IntPtr 是合适的类型。

在 MarshalAs 属性中,我们告诉编码系统将您的“uint 数组”转换为原始的、长指针兼容的 C++ 数组。 SizeParamIndex 告诉它在转换期间分配数组大小时使用“arrSize”参数。

关于c# - 在 C# 中使用 C++ unsigned int *array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20914691/

相关文章:

c# - 使用变量加载数据内文件

c# - ASP.NET 核心 Web API : Authorization based on permissions from database

c++ - DMProcessConfigXML 用于 WM/CE 平台卸载时正在关闭正在运行的应用程序

c++ - 无法理解线路的工作原理

.net - NET中KeyedByTypeCollection的使用?

c# - 单例类继承

c# - 系统窗体定时器参数

c# - 如何使用 SubSonic 和 MySQL 更新更改

c++ - C++中的字符串切片

c# - 褪色的正确数学是什么?