c# - 以 "const void * key, void * out"作为参数进行编码?

标签 c# c++ .net marshalling

我需要通过 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/

相关文章:

c# - 为什么要使用只有一个参数的 string.Format 呢?

c# - 我该如何缩短 If else

c# - 如何使用 GroupBy 和 LEFT JOIN 进行 LINQ 查询

c# - 使用 Linq 在 EF 中编辑用户时无法创建类型的常量值

c# - 如何使用撒克逊将文档类型参数传递给 xslt?

c++ - boost 正则表达式匹配

c++ - fatal error LNK1561 : entry point must be defined

c# - 在单个语句中为多个变量分配相同的值

c++ - 运行时 vector <int> STATUS_ACCESS_VIOLATION

c# - 在与此域关联的配置文件中找不到部分 'caSTLe'