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

C#调用C++ 平台调用P/Invoke 结构体--内存对齐方式、union封装【七】

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

标签:pinvoke   c++   c#   struct   内存   

【1】内存对齐方式


C++代码:

#pragma pack(push)
#pragma pack(1)
typedef struct _testStru2
{
	int		iVal;
	char	cVal;
	__int64 llVal;
}testStru2;
#pragma pack(pop)
EXPORTDLL_API void Struct_PackN( testStru2 *pStru )
{
	if (NULL == pStru)
	{
		return;
	}

	pStru->iVal = 1;
	pStru->cVal = 'a';
	pStru->llVal = 2;

	wprintf(L"Struct_PackN \n");
}

C#代码,指定Pack即可:

[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)]
public struct testStru2
{
    public int	 iVal;
    public sbyte cVal;
    public long  llVal;
};
[DllImport("ExportDll.dll", CharSet = CharSet.Unicode)]
public static extern void Struct_PackN(ref testStru2 pStru);

测试:

CExportDll.testStru2 stru2 = new CExportDll.testStru2();
CExportDll.Struct_PackN(ref stru2);

【2】Union中含有结构体


C++代码:

typedef union _testStru4
{
	int		iValLower;
	int		iValUpper;
	struct 
	{
		__int64 llLocation;
	};
}testStru4;
EXPORTDLL_API void Struct_Union( testStru4 *pStru )
{
	if (NULL == pStru)
	{
		return;
	}
	
	pStru->llLocation = 1024;
	wprintf(L"Struct_Union \n");
}


C#代码:定义成Explict,并显示通过FieldOffset指定内存偏移

[StructLayout(LayoutKind.Explicit, CharSet=CharSet.Unicode)]
public struct testStru4
{
    [FieldOffset(0)]
    int		iValLower;
    [FieldOffset(4)]
    int		iValUpper;
    [FieldOffset(0)]       
    long    llLocation;	        
};
[DllImport("ExportDll.dll", CharSet = CharSet.Unicode)]
public static extern void Struct_Union(ref testStru4 pStru);


测试:

CExportDll.testStru4 stru4 = new CExportDll.testStru4();
CExportDll.Struct_Union(ref stru4);





C#调用C++ 平台调用P/Invoke 结构体--内存对齐方式、union封装【七】

标签:pinvoke   c++   c#   struct   内存   

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

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