码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-09-20 14:08:37      阅读:300      评论:0      收藏:0      [点我收藏+]

标签:pinvoke   c++   c#   struct   指针   

普通的结构体嵌套很简单,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));



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

标签:pinvoke   c++   c#   struct   指针   

原文地址:http://blog.csdn.net/aoshilang2249/article/details/39429785

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!