c# - 如何将 C++ 数据导出到 C# 结构?

标签 c# c++ marshalling dllexport

我正在努力将 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);

其中一些无效,一些返回垃圾值,一些导致崩溃。

最佳答案

refout 参数通常与指针参数匹配。

试试这个:

__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/

相关文章:

c++ - “X 不是模板”错误

c++ - 使用 SSE2 优化 RGB565 到 RGB888 的转换

json - Go中的排序接口(interface)

c# - 如何将表达式编译成实际结果?

c# - 将 UltraCombo 添加到已格式化的 ToolStrip

c++ - 外部 exe/dll 或 WTF 的镜像基地址?

java - 在序列化代理模式中如何调用代理类的 readResolve() 方法?

c++ - 使用 p/invoke 将字符串数组从 C# 编码到 C 代码

c# - 获取扩展方法中第一个参数的名称?

c# - asp.net 中的 Excel 下载库?