时间: 2020-11-26|42次围观|0 条评论

在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#就可以取到数据了(并不是所有的非托管函数都适用)

转载于:https://www.cnblogs.com/Yjianyong/archive/2010/07/13/1776752.html

原文链接:https://blog.csdn.net/weixin_30342827/article/details/95963117

本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。

本博客所有文章如无特别注明均为原创。
复制或转载请以超链接形式注明转自起风了,原文地址《在P/Invoke中使用GCHandle传送对象
   

还没有人抢沙发呢~