我正在努力将 C++ 结构数据导出到 C#。
假设我有以下表示 3 浮点 vector 的结构:
// C++
struct fvec3
{
public:
float x, y, z;
fvec3(float x, float y, float z) : x(x), y(y), z(z) { }
};
// C#
[StructLayout(LayoutKind.Sequential)]
struct fvec3
{
public float x, y, z;
public fvec3(float x, float y, float z)
{
this.x = x;
this.y = y;
this.z = z;
}
}
现在,如果我想使用从 C# 到 C++ 的 fvec3
,我可以毫无问题地使用以下代码:
// C++
__declspec(dllexport) void Import(fvec3 vector)
{
std::cout << vector.x << " " << vector.y << " " << vector.z;
}
// C#
[DllImport("example.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void Import(fvec3 vector);
...
Import(new fvec3(1, 2, 3)); // Prints "1 2 3".
现在的问题是反其道而行之:将 C++ fvec3
返回给 C#。我怎样才能做到这一点?
我见过许多 C# 实现使用类似这样的东西:
// C#
[DllImport("example.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void Export(out fvec3 vector);
...
fvec3 vector;
Export(out vector); // vector contains the value given by C++
但是我该如何编写 C++ Export
函数呢?
我为签名和正文尝试了我能想到的一切:
// Signatures:
__declspec(dllexport) void Export(fvec3 vector)
__declspec(dllexport) void Export(fvec3* vector)
__declspec(dllexport) void Export(fvec3& vector)
// Bodies (with the pointer variants)
vector = fvec3(1, 2, 3);
memcpy(&fvec3(1, 2, 3), &vector, sizeof(fvec3));
*vector = new fvec(1, 2, 3);
其中一些无效,一些返回垃圾值,一些导致崩溃。
最佳答案
ref
和 out
参数通常与指针参数匹配。
试试这个:
__declspec(dllexport) void Export(fvec3 *vector)
{
*vector = fvec3(1, 2, 3);
}
(未测试)
或者,您应该能够简单地从您的函数返回一个 fvec3
:
// C++
__declspec(dllexport) fvec3 Export(void)
{
return fvec3(1, 2, 3);
}
// C#
[DllImport("example.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern fvec3 Export();
...
fvec3 vector = Export();
(未测试)
关于c# - 如何将 C++ 数据导出到 C# 结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15046648/