包装用于C消耗的C ++类API [英] Wrapping C++ class API for C consumption
问题描述
我有一组相关的C ++类,它们必须从DLL中打包和导出,以便C / FFI库可以轻松使用。我正在寻找一些最佳做法这样做。例如,如何创建和释放对象,如何处理基类,替代解决方案等...
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...
我迄今为止的一些基本指导是将方法转换为简单函数带有表示this指针的额外void *参数,包括任何析构函数。构造函数可以保留其原始参数列表,但必须返回一个表示该对象的指针。所有内存都应该通过同一组进程范围的分配和自由例程来处理,并且在某种意义上应该通过宏或其他方式进行热插拔。
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.
任何建议。
推荐答案
Foreach的公共方法你需要一个C函数。
你还需要一个不透明的指针在C代码中表示你的类。
只要使用一个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);
实现是微不足道的。
将opaque指针转换为Fred然后调用该方法。
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消耗的C ++类API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!