C#呼び出しC++プラットフォーム呼び出しP/Invoke構造体--構造体ネスト【8】
Git p-invokeソースアドレス
一般的な構造体はネストが簡単で、C#で直接対応する構造体として定義すればよい.ここではネストされた構造体がポインタで表現されていることを紹介する
【1】ネスト構造体ポインタ
C++コード:
C#コード:IntPtrとして定義するには解析が必要:
テスト:
一般的な構造体はネストが簡単で、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
");
}
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));