Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass structure (or class) from C++ dll to C# (Unity 3D)

I am writing a wrapper to get some data from a sensor. While I have no problems with passing int, float and arrays of them, I have difficulties to grasp how to pass a structure.

Code summary

C++ side

The structure is as follows:

struct HandInfo
{
    int id;
    float x, y, z;
};

At some point one static, globally visible HandInfo leftHand is filled with values which are retrievable through the following wrapper function:

extern EXPORT_API HandInfo MyWrapper_getLeftHand()
{
    return handtracker.getLeftHand();
}

where handtracker is just an instance of the wrapped class.

C# side

Once declared the extern function

[DllImport("MyWrapper")]
private static extern HandInfo MyWrapper_getLeftHand();

On the C# side, ideally, I would have the same struct type

public struct HandInfo
{
    public int id;
    public float x, y, z;
}

and assign a variable

HandInfo hi = MyWrapper_getLeftHand(); // NAIVELY WRONG CODE

which, understandably, doesn't work.

What's the way to achieve this?

I'd appreciate any help. Thank you all for your time.

like image 363
SteakOverflow Avatar asked Feb 10 '23 04:02

SteakOverflow


1 Answers

It should work correctly (at least, here in a small C++ + C# project I have, I was able to make it work with that struct, both in x86 and x64)

[DllImport("MyWrapper.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern HandInfo MyWrapper_getLeftHand();

The only thing, you must declare the CallingConvention = CallingConvention.Cdecl.

like image 82
xanatos Avatar answered Feb 13 '23 02:02

xanatos