我正在使用來自第三方供應商的C API DLL。我的問題是,我似乎無法找到編組下面的C代碼的好模板:void **使用P/Invoke處理
API_Open(void ** handle);
API_Close(void * handle);
的呼聲被簡化,但手柄是一個void *,這是(在C)通過進入API_Open
調用爲&的句柄,然後作爲句柄傳入API_Close
。
我試過在C#中做同樣的事情,但不知道如何正確處理元帥。我的C#版本(最新的嘗試)是:
[DllImport("External.dll",EntryPoint="API_Open")]
public static extern int API_Open(out IntPtr handle);
[DllImport("External.dll",EntryPoint="API_Close")]
public static extern int API_Close(IntPtr handle);
public static int Wrapper_API_Open(ref Int32 handle)
{
int rc = SUCCESS;
// Get a 32bit region to act as our void**
IntPtr voidptrptr = Marshal.AllocHGlobal(sizeof(Int32));
// Call our function.
rc = API_Open(out voidptrptr);
// In theory, the value that voidptrptr points to should be the
// RAM address of our handle.
handle = Marshal.ReadInt32(Marshal.ReadIntPtr(voidptrptr));
return rc;
}
public static int Wrapper_API_Close(ref Int32 handle)
{
int rc = SUCCESS;
// Get a 32bit region to act as our void *
IntPtr voidptr = Marshal.AllocHGlobal(sizeof(Int32));
// Write the handle into it.
Marshal.WriteInt32(voidptr,handle);
// Call our function.
rc = API_Close(voidptr);
return rc;
}
public void SomeRandomDrivingFunction()
{
.
.
.
Int32 handle;
Wrapper_API_Open(ref handle);
.
.
.
Wrapper_API_Close(ref handle);
.
.
.
}
API返回代碼總是INVALID_DEVICE_OBJECT當我打電話API_Close。有什麼想法嗎?我認爲這會非常簡單,但是我無法繞過函數調用的void **和void *部分。
謝謝
看起來你應該只是'IntPtr句柄; API_Open(出處理);'然後'API_Close(處理);'。 –
只需刪除Marshal.AllocHGlobal()hokey-pokey,IntPtr就是句柄。改進錯誤檢查,當API_Open()返回錯誤代碼時拋出異常。 –