我需要通过 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
它说我想写入 protected 内存。 dll 和 c# 软件是 x64(并且需要是 x64)。也许这是我的原因?
最佳答案
对 key 和 out 使用 IntPtr
,比如:
[DllImport ("whatever.dll")]
public static extern void MyMethod(IntPtr key, IntPtr outprm);
要使 key
成为 IntPtr,将 myArray
设为字节数组:
IntPtr key = Marshal.AllocHGlobal(myArray.Length);
Marshal.Copy(myArray, 0, key, myArray.Length);
// ... call your function ...
Marshal.FreeHGlobal(key );
从 outprm
获取 16 字节数组:
IntPtr outprm;
MyMethod(key, outprm);
byte [] myArray = new byte[16];
Marshal.Copy(outprm, myArray, 0, 16);
关于c# - 以 "const void * key, void * out"作为参数进行编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12302530/