1. 程式人生 > >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>