C#封送结构体数组到C++ DLL

    [StructLayout(LayoutKind.Sequential)]
    struct FaceLibQuery
    {
        public int iSize;
        public int iChanNo;
        public int iPageNo;
        public int iPageCount;
    };
FaceLibQuery tQuery = new FaceLibQuery();
            tQuery.iSize = Marshal.SizeOf(tQuery);
            tQuery.iChanNo = m_iChannelNo;
            tQuery.iPageNo = 0;     //要查询的页码,iPageNo >= 0。
            tQuery.iPageCount = 20;   //查询的每页个数,取值范围[1,20]。

            IntPtr ipQueryInfo = Marshal.AllocHGlobal(Marshal.SizeOf(tQuery));
            Marshal.StructureToPtr(tQuery, ipQueryInfo, true);//false容易造成内存泄漏

            //封送结构体数组
            FaceLibQueryResult[] tResult = new FaceLibQueryResult[20];
            for (int i = 0; i < tResult.Length; i++)
            {
                tResult[i] = new FaceLibQueryResult();
            }
            IntPtr ipResult = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(FaceLibQueryResult)) * 20);

            int iRet = -1;
            iRet = NVSSDK.NetClient_FaceConfig(m_iLogonId, NVSSDK.FACE_CMD_LIB_QUERY, m_iChannelNo, ipQueryInfo, Marshal.SizeOf(tQuery), ipResult, Marshal.SizeOf(typeof(FaceLibQueryResult)));
            Console.WriteLine(iRet);
            //还原结构体数组   
            for (int i = 0; i < 20; i++)    
            {
                IntPtr ptr = (IntPtr)((UInt32)ipResult + i * Marshal.SizeOf(typeof(FaceLibQueryResult)));
                tResult[i] = (FaceLibQueryResult)Marshal.PtrToStructure(ptr, typeof(FaceLibQueryResult));
                Console.WriteLine("人脸库:" + Encoding.Default.GetString(tResult[i].tFaceLib.cName));
            }
            Marshal.FreeHGlobal(ipQueryInfo);
            Marshal.FreeHGlobal(ipResult);

猜你喜欢

转载自www.cnblogs.com/HansZimmer/p/12485234.html