Skip to main content
 首页 » 编程设计

c# dllimport with pointers 收藏

2024年02月06日11arxive

我有一个无法导入到我的 vs2012 c# 项目中的 dll。我以前使用过 dllImport,但以前从未使用过 Marshal 或指针。我想我很幸运。

这是我目前拥有的代码。 被调用的函数是 fnLDA_GetDevInfo(DEVID *ActiveDevices) DEVID 是一个普通的无符号整数(#define DEVID 无符号整数)

//Allocate an array big enough to hold the device ids for the number of devices present. 
//Call fnLDA_GetDevInfo(DEVID *ActiveDevices), which will fill in the array with the device ids for each connected attenuator 
//The function returns an integer, which is the number of devices present on the machine. 
[DllImport(DLLLOCATION,CallingConvention = CallingConvention.Cdecl)] 
private static extern int fnLDA_GetDevInfo([MarshalAs(UnmanagedType.LPArray)] ref uint[] ActiveDevices); 

我在代码中这样调用函数

uint[] MyDevices; 
fnLDA_GetDevInfo(ref MyDevices); 

此时我得到一个错误:

Attempted to read or write protected memory. This is often an indication that other memory is corrupt. 

现在我很确定错误发生是因为我没有调用正确的指针或其他东西。

如有任何帮助,我们将不胜感激。

请您参考如下方法:

你有一个额外的间接层。数组被编码为指向数组的指针。当您将参数声明为 ref 时,将再次传递一个指针。因此,您的 C# 代码匹配 uint**。即便如此,您也不能将 ref 与数组类型一起使用,因为您不能期望非托管代码生成托管数组。

你的 p/invoke 应该是:

[DllImport(DLLLOCATION,CallingConvention = CallingConvention.Cdecl)] 
private static extern int fnLDA_GetDevInfo([Out] uint[] ActiveDevices); 

请注意,此函数很难调用。由于函数没有传递数组的长度,如果数组不够长,函数不可能避免跑到数组末尾。我真的希望您有一些方法可以在调用此函数之前计算出数组需要多大。

所以也许你应该这样调用它:

uint[] MyDevices = new uint[SomeLargeNumberThatYouPresumablyCanProvide]; 
int len = fnLDA_GetDevInfo(MyDevices); 

或者像这样:

int len = fnLDA_GetDevInfo(null); 
uint[] MyDevices = new uint[len]; 
fnLDA_GetDevInfo(MyDevices); 

我相信您将能够从 DLL 的文档和/或调用 DLL 的示例 C++ 程序中解决剩下的问题。