C# DLL使用指针导入



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

这是我目前拥有的代码。被调用的函数是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/调用应该是:

[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++完成其余的工作。

最新更新