【发布时间】:2012-09-06 14:38:55
【问题描述】:
我需要通过 dllimport 调用一个 c++ 方法。只要c++方法中没有以下两个参数,一切正常:
const void * key,
void * out
我想我需要整理他们。但它是如何工作的? key应该是指向字节数组的指针,out参数也是长度为16的字节数组。
在尝试了 Jcl 的建议后,我有以下几点:
使用第一种方法(使用 out byte[] outprm),程序在没有错误的情况下崩溃(到达调用点时)。 但使用第二种方式(来自 Jcl 的评论),我有以下内容:
[DllImport(@"MyDLL.dll", SetLastError = true)]
public static extern void MyMethod(IntPtr key, out IntPtr outprm);
private void button1_Click(object sender, EventArgs e)
{
byte[] hash = new byte[16];
byte[] myArray = new byte[] { 1, 2, 3 };
IntPtr outprm = Marshal.AllocHGlobal(hash.Length);
IntPtr key = Marshal.AllocHGlobal(myArray.Length);
Marshal.Copy(myArray, 0, key, myArray.Length);
MyMethod(key, out outprm);
Marshal.Copy(outprm, hash, 0, 16);
Marshal.FreeHGlobal(key);
}
现在调用 MyMethod 时没有错误。当我尝试将数据复制回来时,我只是收到以下错误:AccessViolationException
它说我想写入受保护的内存。 dll 和 c# 软件是 x64(并且需要是 x64)。也许这就是原因?
【问题讨论】:
标签: c# c++ .net marshalling