繁体   English   中英

Marshal以“const void * key,void * out”作为参数?

[英]Marshal with “const void * key, void * out” as parameter?

我需要通过dllimport调用c ++方法。 只要c ++方法中没有以下两个参数,一切正常:

const void * key,
void * out

我想我需要整理他们。 但它是如何工作的? 键应该是指向字节数组的指针,out参数也是一个长度为16的字节数组。

在尝试了Jcl建议之后,我有以下内容:

使用第一种方法(使用out [byte out]),程序崩溃而没有错误(到达调用点时)。 但是使用第二种方式(来自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)。 也许这就是我的原因?

使用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);    

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM