首页 > 代码库 > C#调用C++ 平台调用P/Invoke 结构体--含有内置数据类型的一维、二维数组、字符串指针【六】

C#调用C++ 平台调用P/Invoke 结构体--含有内置数据类型的一维、二维数组、字符串指针【六】

【1】结构体中含有内置数据类型的一维数组


C++代码:

typedef struct _testStru3
{
	int		iValArrp[30];
	WCHAR	szChArr[30];
}testStru3;
EXPORTDLL_API void Struct_ChangeArr( testStru3 *pStru )
{
	if (NULL == pStru)
	{
		return;
	}

	pStru->iValArrp[0] = 8;
	lstrcpynW(pStru->szChArr, L"as", 30);

	wprintf(L"Struct_ChangeArr \n");
}

C#代码:定义成数组并通过SizeConst指定其长度(对于字符数组,可以直接指定为string)

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct testStru3
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst=30)]
    public int		[]iValArrp;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 30)]
    public string szChArr;
};
[DllImport("ExportDll.dll", CharSet = CharSet.Unicode)]
public static extern void Struct_ChangeArr(ref testStru3 pStru);

测试:

CExportDll.testStru3 stru3 = new CExportDll.testStru3();
CExportDll.Struct_ChangeArr(ref stru3);

【2】结构体中含有内置数据类型的二维数组


C++代码:

typedef struct _testStru7
{
	int		m[5][5];
}testStru7;
EXPORTDLL_API void Struct_Change2DArr( testStru7 *pStru )
{
	if (NULL == pStru)
	{
		return;
	}

	pStru->m[3][3] = 1;
	wprintf(L"Struct_Change2DArr \n");
}

C#代码:把二维数组拆分成两个一维数组

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct testStru7Pre
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst=5)]
    public int		[]m;
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct testStru7
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)]
    public testStru7Pre []m;
};
[DllImport("ExportDll.dll", CharSet = CharSet.Unicode)]
public static extern void Struct_Change2DArr(ref testStru7 pStru);

测试:

CExportDll.testStru7 stru7 = new CExportDll.testStru7();
CExportDll.Struct_Change2DArr(ref stru7);

【3】结构体中含有字符串指针


C++代码:

typedef struct _testStru9
{	
	WCHAR	*pWChArr;
	CHAR	*pChArr;
	bool	IsCbool;
	BOOL	IsBOOL;
}testStru9;
EXPORTDLL_API void Struct_ChangePtr( testStru9 *pStru )
{
	if (NULL == pStru)
	{
		return;
	}

	pStru->IsBOOL = true;
	pStru->IsBOOL = TRUE;
	pStru->pWChArr = (WCHAR*)CoTaskMemAlloc(8*sizeof(WCHAR));
	pStru->pChArr = (CHAR*)CoTaskMemAlloc(8*sizeof(CHAR));

	lstrcpynW(pStru->pWChArr, L"ghj", 8);
	lstrcpynA(pStru->pChArr, "ghj", 8);

	wprintf(L"Struct_ChangePtr \n");
}

C#代码,定义成string即可,注意BOOLbool的不同:

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct testStru9
{
    [MarshalAs(UnmanagedType.LPWStr)]
    public string pWChArr;
    [MarshalAs(UnmanagedType.LPStr)]
    public string pChArr;
    [MarshalAs(UnmanagedType.U1)]
    public bool IsCbool;
    [MarshalAs(UnmanagedType.Bool)]
    public bool IsBOOL;
};
[DllImport("ExportDll.dll", CharSet = CharSet.Unicode)]
public static extern void Struct_ChangePtr(ref testStru9 pStru);

测试:

<strong>CExportDll.testStru9 stru9 = new CExportDll.testStru9();
CExportDll.Struct_ChangePtr(ref stru9);
</strong>


C#调用C++ 平台调用P/Invoke 结构体--含有内置数据类型的一维、二维数组、字符串指针【六】