从C ++ 3D矢量结构,C# [英] 3D Vector structure from c++ to C#

查看:122
本文介绍了从C ++ 3D矢量结构,C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想端口一些功能从我的引擎从C ++到C#。
我编译我的发动机与非托管C一个dll ++,只在C#包装使用externC的功能。

I'm trying to port some functionality from my engine from c++ to C#. I compile my engine as a dll with unmanaged c++ and only use extern "C" functions in the C# wrapper.

我的各种功能的需要而归 Vector3df 。这被定义为

I have various functions that take and return Vector3df. This is defined as

typedef Vector3d<f32> Vector3df;

F32 是一个实际上是浮动。类本身没有什么比一些委员呼吁XY和z和很多的方法。

and f32 is a actually a float. The class itself has nothing more than some members called x y and z and a lot of methods.

我可以重写在C#全班同学,这不是一个问题,但有?反正其中2可以匹配

I can rewrite the whole class in C#, that's not a problem but is there anyway in which the 2 could be matched?

让我们举个例子以下功能:

Let's take for example the following functions:

extern "C" void SetColor(Vector3df color)
extern "C" Vector3df GetColor()

我想在C#中是这样的:

I would like to have something like this in C#:

[DllImport("Engine.dll", EntryPoint = "SetColor", CallingConvention = CallingConvention.Cdecl)]
static extern void SetColor(Vector3df color);
[DllImport("Engine.dll", EntryPoint = "GetColor", CallingConvention = CallingConvention.Cdecl)]
static extern Vector3df GetColor();



反正是有中,我可以做类似这样的工作代码?

Is there anyway in which I could make code similar to this work?

请注意,我用的又不是意味着当它涉及到一个编组C#guru.I'm丢失。我主要做这使我的游戏地图编辑器,而无需学习Qt或wxWidgets的。

Note that I'm not by any means a C# guru.I'm lost when it comes to marshaling. I'm mostly doing this to make a map editor for my game without having to learn Qt or wxWidgets.

感谢您!

推荐答案

所有你需要做的就是定义一个具有等效二进制布局到一个由C ++ DLL预期的C#结构。假设只有X,Y,Z,没有包装,那真是...

All you need to do is define a C# structure that has an equivalent binary layout to the one expected by the c++ dll. Assuming only x,y,z with no packing, that's just...

[StructLayout(LayoutKind.Sequential)] //Required, as default layout is Auto
struct Vector3df {
    public float x, y, z;
}

这应该你给C和C#函数签名工作。困难出现,如果你想调用任何方法对Vector3df类,因为你不能的P / Invoke C ++类的方法。你需要为你的设置/ GETCOLOR做包装每个方法作为一个纯C函数。

That should work with the C and C# function signatures you've given. The difficulty arises if you wish to invoke any method on the Vector3df class, because you cannot p/invoke C++ class methods. You need to wrap each of the methods as a plain C function as you've done with the Set/GetColor.

如果你把它最终成为了很多工作重新尝试导入一个很大的图书馆,而且可能更容易使用C ++ / CLI创建包装。另一种选择是使用 cxxi 进行调查,但我用这个没有经验。

It ends up being a lot of work if you're trying to import a big library, and might be simpler to use C++/CLI to create the wrapper. Another option might be to investigate using cxxi, but I have no experience using this.

这篇关于从C ++ 3D矢量结构,C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆