在C#中調用非托管函數的時,有很多函數需要使用在C#中定義對象的地址;因此要使用到GCHandle類。
使用片斷:
DWORD ReadCert(
UNT_DEV_HANDLE hDev,
BYTE* pbCert,
DWORD* pdwCertLen,
DWORD dwFlag);
/// Return Type: DWORD->unsigned int
///hDev: UNT_DEV_HANDLE->void*
///pbCert: BYTE*
///pdwCertLen: DWORD*
///dwFlag: DWORD->unsigned int
[System.Runtime.InteropServices.DllImportAttribute("GAKeyPub", EntryPoint = "ReadCert")]
public static extern int ReadCert(System.IntPtr hDev, [Out] IntPtr pbCert, ref int pdwCertLen, int dwFlag);
byte[] certBytes = new byte[certLen];
GCHandle hcertBytes = GCHandle.Alloc(certBytes, GCHandleType.Pinned);
IntPtr pcert = hcertBytes.AddrOfPinnedObject();
result = GAKeyPubInvoke.ReadCert(devHandle, pcert, ref certLen, 1);
這樣C#就可以取到數據了(並不是所有的非托管函數都適用)