将结构(或类)从C++ dll传递到C#(Unity 3D)

Ste*_*low 2 c# c++ dll plugins interop

我正在编写一个包装器来从传感器获取一些数据.虽然我没有传递int,float和它们的数组的问题,但我很难掌握如何传递结构.

代码摘要

C++方面

结构如下:

struct HandInfo
{
    int id;
    float x, y, z;
};
Run Code Online (Sandbox Code Playgroud)

在某些时候,一个静态的,全局可见的HandInfo leftHand充满了可通过以下包装函数检索的值:

extern EXPORT_API HandInfo MyWrapper_getLeftHand()
{
    return handtracker.getLeftHand();
}
Run Code Online (Sandbox Code Playgroud)

其中handtracker只是包装类的一个实例.

C#方面

一旦声明了extern功能

[DllImport("MyWrapper")]
private static extern HandInfo MyWrapper_getLeftHand();
Run Code Online (Sandbox Code Playgroud)

在C#方面,理想情况下,我将具有相同的结构类型

public struct HandInfo
{
    public int id;
    public float x, y, z;
}
Run Code Online (Sandbox Code Playgroud)

并分配一个变量

HandInfo hi = MyWrapper_getLeftHand(); // NAIVELY WRONG CODE
Run Code Online (Sandbox Code Playgroud)

可以理解,这是行不通的.

有什么办法实现这个目标?

我很感激任何帮助.谢谢大家的时间.

xan*_*tos 5

它应该正常工作(至少,在我的小C++ + C#项目中,我能够使用它struct,在x86和x64中)

[DllImport("MyWrapper.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern HandInfo MyWrapper_getLeftHand();
Run Code Online (Sandbox Code Playgroud)

唯一的,你必须申报CallingConvention = CallingConvention.Cdecl.