I encountered an issue where allocating memory for a struct with new in the C++ function does not correctly transfer the instance back to C#.
It seems that the correct approach is to avoid using new in the C++ function and directly set the values of the out parameter. However, I couldn’t find documentation that explicitly describes this behavior or explains how out parameters automatically handle instance creation.
Do you have this information somewhere on Microsoft Document?
I would like to know if you know of it.
C++
struct MyStruct {
int value1;
float value2;
};
extern "C" __declspec(dllexport) void GetValues(MyStruct* outStruct) {
// outStruct = new MyStruct(); // NG
outStruct->value1 = 42;
outStruct->value2 = 3.14f;
}
C#
[StructLayout(LayoutKind.Sequential)]
public struct MyStruct {
public int value1;
public float value2;
}
[DllImport("MyNativeLib.dll", CallingConvention = CallingConvention.StdCall)]
public static extern void GetValues(out MyStruct result);
public static void TestInterop() {
MyStruct result;
GetValues(out result);
}