[英]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.