How to get in C# struct of a C++ function that returns a struct as a pointer?

138 Views Asked by At

The following simple example looks very natural, however it is not getting the right values from the structure. C++ code:

#define E __declspec( dllexport )

struct  XY {
    int x, y;
};

extern "C" {
    E XY* get_xy_ptr() {
        XY p;
        p.x = 15;
        p.y = 23;
        return &p;
    }
}

The C# code to use this function would be:

record struct XY(int x, int y); // C# 10
// OR...
//struct XY
//{
//    public int x;
//    public int y;
//}

[DllImport("CppLibrary.dll")] static extern IntPtr get_xy_ptr();

IntPtr pointer = get_xy_ptr();

XY xy = Marshal.PtrToStructure<XY>(pointer);

Console.WriteLine("xy.x : {0}", xy.x);
Console.WriteLine("xy.y : {0}", xy.y);

However, it does not get the expected results:

C++ Calls Demostration
----------------------
xy_ptr.x : 0 // expected 15 
xy_ptr.y : 0 // expected 23

It is worth clarifying that if the C++ function does not return a pointer, that is, instead of XY*, it returns an explicit XY, and in C# I declare the explicit structure as return, instead of IntPtr, it works perfectly. However, it is not what I am looking for, I need it to be a pointer as it will be used in Emscripten for use in WebAssemply, and it does not accept explicit structures as return.

Thanks for your attention.

0

There are 0 best solutions below