包装C ++类的API对C消费 [英] Wrapping C++ class API for C consumption

查看:198
本文介绍了包装C ++类的API对C消费的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组必须被包裹并以这样的方式,它可以被C /​​ FFI库容易地消耗从DLL导出相关的C ++类的。我在寻找做一些这方面的最佳做法。例如,如何创建和免费的对象,如何处理基类,可选择的解决方案,等等...

I have a set of related C++ classes which must be wrapped and exported from a DLL in such a way that it can be easily consumed by C / FFI libraries. I'm looking for some "best practices" for doing this. For example, how to create and free objects, how to handle base classes, alternative solutions, etc...

一些基本准则,我至今是方法转化为简单的功能转换与一个额外的void *参数重新presenting的this指针,包括任何析构函数。构造函数可以保留原来的参数列表,但必须返回一个指针重新presenting的对象。所有存储器应通过同一组进程范围分配和释放例程或者通过宏或以其他方式进行处理,而且应该是热插拔在某种意义上来说,

Some basic guidelines I have so far is to convert methods into simple functions with an extra void* argument representing the 'this' pointer, including any destructors. Constructors can retain their original argument list, but must return a pointer representing the object. All memory should be handled via the same set of process-wide allocation and free routines, and should be hot-swappable in a sense, either via macros or otherwise.

任何意见是pciated AP $ P $

Any advice is appreciated

推荐答案

你Foreach源需要一个C函数公共方法。

您还需要一个不透明的指针重新present类在C code。

这是简单的只使用一个void *虽然你可以建立一个包含一个void *和其它信息(例如,如果你想支持数组?)一个结构。

Foreach public method you need a C function.
You also need an opaque pointer to represent your class in the C code.
It is simpler to just use a void* though you could build a struct that contains a void* and other information (For example if you wanted to support arrays?).

Fred.h
--------------------------------

#ifdef  __cplusplus
class Fred
{
    public:
    Fred(int x,int y);
    int doStuff(int p);
};
#endif

//
// C Interface.
typedef void*   CFred;

//
// Need an explicit constructor and destructor.
extern "C" CFred  newCFred(int x,int y);
extern "C" void   delCFred(CFred);

//
// Each public method. Takes an opaque reference to the object
// that was returned from the above constructor plus the methods parameters.
extern "C" int    doStuffCFred(CFred,int p);

的实施是微不足道的。

不透明指针转换为弗雷德,然后调用该方法。

The the implementation is trivial.
Convert the opaque pointer to a Fred and then call the method.

CFred.cpp
--------------------------------

// Functions implemented in a cpp file.
// But note that they were declared above as extern "C" this gives them
// C linkage and thus are available from a C lib.
CFred newCFred(int x,int y)
{
    return reinterpret_cast<void*>(new Fred(x,y));
}

void delCFred(CFred fred)
{
    delete reinterpret_cast<Fred*>(fred);
}

int doStuffCFred(CFred fred,int p)
{
    return reinterpret_cast<Fred*>(fred)->doStuff(p);
}

这篇关于包装C ++类的API对C消费的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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