プリミティブ構造をC++からC#にマーシャリングしようとしていますが、次のコードがあります。
using System;
using System.Runtime.InteropServices;
namespace dotNet_part
{
class Program
{
static void Main(string[] args)
{
Custom custom = new Custom();
Custom childStruct = new Custom();
IntPtr ptrToStructure = Marshal.AllocCoTaskMem(Marshal.SizeOf(childStruct));
Marshal.StructureToPtr(childStruct, ptrToStructure, true);
custom.referenceType = ptrToStructure;
custom.valueType = 44;
Custom returnedStruct = structureReturn(custom);
Marshal.FreeCoTaskMem(ptrToStructure);
returnedStruct = (Custom)Marshal.PtrToStructure(returnedStruct.referenceType, typeof(Custom));
Console.WriteLine(returnedStruct.valueType); // Here 'm receiving 12 instead of 44
}
[return:MarshalAs(UnmanagedType.I4)]
[DllImport("CPlusPlus part.dll")]
public static extern int foo(Custom param);
// [return:MarshalAs(UnmanagedType.Struct)]
[DllImport("CPlusPlus part.dll")]
public static extern Custom structureReturn(Custom param);
}
[StructLayout(LayoutKind.Sequential)]
struct Custom
{
[MarshalAs(UnmanagedType.I4)]
public int valueType;
public IntPtr referenceType;
}
}
そしてC++の部分:
typedef struct Custom CUSTOM;
extern "C"
{
struct Custom
{
int valueType;
Custom* referenceType;
} Custom;
_declspec(dllexport) int foo(CUSTOM param)
{
return param.referenceType->valueType;
}
_declspec(dllexport) CUSTOM structureReturn(CUSTOM param)
{
return param;
}
}
なぜ私は44ではなく12を受け取っているのreturnedStruct.valueType
ですか?