【发布时间】:2010-12-06 04:15:40
【问题描述】:
我正在尝试让 dll 工作。
DLL 是用 C++ 编写的,它需要将 int* 传递给 C#。我花了几天的时间来让它工作,但它失败了。我开始拔头发,因为我不知道出了什么问题。我已经尝试了一切。我对 C++ 不像对 C# 那样熟悉,所以问题可能来自那里......
从 dll 中读取正常,但返回的值不正确。我删除了输入,我只是想通过一个测试数组。我在 C++ 中使用的函数是:
extern "C" EAGLE128DLL_API int* encryptFunc()
{
//return encrypt(x, Q);
int t[128];
for(int i = 0; i < 128; i++)
{
t[i] = 5;
}
return t;
};
我用来调用这个函数的C#代码如下:
[DllImport("C:\\Users\\Leon\\Documents\\Visual Studio 2010\\Projects\\Eagle128DLL\\Release\\Eagle128DLL.dll")]
public static extern IntPtr encryptFunc();
...
IntPtr outputPtr = encryptFunc();
int[] output = new int[128];
Marshal.Copy(outputPtr, output, 0, 128);
输出数组中的值应该全是 5。但我得到的是: 16187392、16190224..etc(不是 5 的)
【问题讨论】:
-
您还应该能够使用 [return: MarshalAs] 属性返回 int[] 而不是 IntPtr 并让编组器为您完成工作: [return: MarshalAs(UnmanagedType.LPArray , SizeConst = 128)] public static extern int[] encryptFunc();
标签: c# c++ marshalling