garrilla
garrilla

Reputation: 569

Passing a struct with array of structures from c# to c++

I have a c# hierarchy of structs.

private struct Vector3
{
    public float x;
    public float y;
    public float z;
}

private structure Location
{
    public Vector3 coords;
    public float distanceFromOrigin;
}

private struct Locations
{
    public Location[] locations;
}

private struct Scene
{
    public Locations cam1;
    public Locations cam2;
    public float timeInMilliSecs;
}

I'm instantiating the Scene and with cam1 and cam2 each gets an array of 10 Locations. Everything traces fine. Works as expected to this point and the data structure is populated with the correct data.

I'm passing the instance of Scene to an unmanaged DLL

[DllImport(dllname)]
private static extern void updateScene(Scene scene);

In my c++ I have

extern "C" {
    DLL_EXPORT void updateScene(Scene scene);
}

and an overload

void updateScene(Scene scene) {
    setSecene(scene); // this calls function fine but with erroneous data
}

and signatures for the equivalent structs

struct Vector3
{
    float x;
    float y;
    float z;
}

struct Location
{
    Vector3 coords;
    float distanceFromOrigin;
}

struct Locations
{
    Location locations[10];
}

struct Scene
{
    Locations cam1;
    Locations cam2;
    float timeInMilliSecs;
}

The Scene struct is passed into the C with the correct data structure but not the correct data, none of the Vector3s are right and timeInMilliSecs is always 0.

Previously I had Locations as individual instances of Location and that worked fine but since making it an array it doesn't work.

I'm guessing that I need to Marshall this across but I don't know where to start. Can anyone help, please?

Upvotes: 1

Views: 190

Answers (1)

shingo
shingo

Reputation: 27086

Try:

[MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
public Location[] locations;

Array in c# is a reference type.

Upvotes: 1

Related Questions