C#调用C++ 平台调用P/Invoke 结构体--结构体嵌套【八】

来源:互联网 发布:php能做幻灯片吗 编辑:程序博客网 时间:2024/05/01 12:21

普通的结构体嵌套很简单,C#中直接定义成对应的结构体即可,这里介绍的是嵌套的结构体以指针的方式表达


【1】嵌套结构体指针


C++代码:

typedef struct _testStru10Pre{int  iVal;}testStru10Pre;typedef struct _testStru10{testStru10Pre *pPre;long  lVal;_testStru10(){pPre = NULL;}}testStru10;
EXPORTDLL_API void Struct_NestStruct( testStru10 *pStru ){if (NULL == pStru){return;}pStru->lVal = 10;if (NULL != pStru->pPre){pStru->pPre->iVal = 9;}wprintf(L"Struct_NestStruct \n");}

C#代码:定义为IntPtr需要进行解析:

public struct testStru10Pre{    public int iVal;};public struct testStru10{    public IntPtr pPre;    public int lVal;};[DllImport("ExportDll.dll", CharSet = CharSet.Unicode)]public static extern void Struct_NestStruct(ref testStru10 pStru);

测试:

CExportDll.testStru10Pre str10Pre = new CExportDll.testStru10Pre();IntPtr intPtrStru10Pre = Marshal.AllocCoTaskMem(Marshal.SizeOf(str10Pre));Marshal.StructureToPtr(str10Pre, intPtrStru10Pre, false);CExportDll.testStru10 stru10 = new CExportDll.testStru10();stru10.pPre = intPtrStru10Pre;CExportDll.Struct_NestStruct(ref stru10);CExportDll.testStru10Pre str10Pre2 = (CExportDll.testStru10Pre)Marshal.PtrToStructure(stru10.pPre, typeof(CExportDll.testStru10Pre));Marshal.DestroyStructure(intPtrStru10Pre, typeof(CExportDll.testStru10Pre));



0 0
原创粉丝点击