将结构(或类)从C ++ dll传递到C#(Unity 3D)
我正在编写包装程序以从传感器获取一些数据.虽然我在传递int,float和它们的数组时没有问题,但是我很难掌握如何传递结构.
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.
代码摘要
C ++方面
结构如下:
struct HandInfo
{
int id;
float x, y, z;
};
在某个时候,一个静态的,全局可见的HandInfo leftHand填充了可通过以下包装函数检索的值:
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();
}
其中 handtracker 只是包装类的一个实例.
where handtracker is just an instance of the wrapped class.
C#端
一旦声明了extern函数
Once declared the extern function
[DllImport("MyWrapper")]
private static extern HandInfo MyWrapper_getLeftHand();
在C#端,理想情况下,我将具有相同的结构类型
On the C# side, ideally, I would have the same struct type
public struct HandInfo
{
public int id;
public float x, y, z;
}
并分配一个变量
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.
它应该可以正常工作(至少,在我拥有的一个小型C ++ + C#项目中,我能够使其与该struct
一起工作)在x86和x64中)
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();
唯一的事情是,必须声明CallingConvention = CallingConvention.Cdecl
.
The only thing, you must declare the CallingConvention = CallingConvention.Cdecl
.