问题描述
我希望开发一组C的API,将环绕我们现有的C ++ API访问我们的核心逻辑(写在面向对象的C ++)的。这将主要是胶水的API,可以让我们的C ++的逻辑是由其他语言的使用。有什么好的教程,书籍或参与引进围绕面向对象的C ++?
I'm looking to develop a set of C APIs that will wrap around our existing C++ APIs to access our core logic (written in object-oriented C++). This will essentially be a glue API that allows our C++ logic to be usable by other languages. What are some good tutorials, books, or best-practices that introduce the concepts involved in wrapping C around object-oriented C++?
推荐答案
这是不是太难做手工,但将取决于您的接口的大小。
在那里我做的情况下,它是从纯C code内能够使用我们的C ++库,因而SWIG是没有太大的帮助。 (嗯,也许痛饮可用于做到这一点,但我没有痛饮大师,似乎不平凡)
This is not too hard to do by hand, but will depend on the size of your interface.The cases where I've done it were to enable use of our C++ library from within pure C code, and thus SWIG was not much help. (Well maybe SWIG can be used to do this, but I'm no SWIG guru and it seemed non-trivial)
所有我们落得这样做是:
All we ended up doing was:
- 的每一个对象在C传递有关的不透明句柄。
- 构造函数和析构函数被包裹在纯函数
- 的成员函数是纯函数。
- 其他建宏被映射到C当量在可能的情况。
所以像这样(C ++头)一类
So a class like this (C++ header)
class MyClass
{
public:
explicit MyClass( std::string & s );
~MyClass();
int doSomething( int j );
}
将映射到一个C接口这样的(C头):
Would map to a C interface like this (C header):
struct HMyClass; // An opaque type that we'll use as a handle
typedef struct HMyClass HMyClass;
HMyClass * myStruct_create( const char * s );
void myStruct_destroy( HMyClass * v );
int myStruct_doSomething( HMyClass * v, int i );
该接口的实现是这样的(C ++源)
The implementation of the interface would look like this (C++ source)
#include "MyClass.h"
extern "C"
{
HMyClass * myStruct_create( const char * s )
{
return reinterpret_cast<HMyClass*>( new MyClass( s ) );
}
void myStruct_destroy( HMyClass * v )
{
delete reinterpret_cast<MyClass*>(v);
}
int myStruct_doSomething( HMyClass * v, int i )
{
return reinterpret_cast<MyClass*>(v)->doSomething(i);
}
}
(这似乎并没有与我目前的编译工作)。我们必须使处理结构作为C不支持类。
(This didn't seem to work with my current complier). We have to make the handle a struct as C doesn't support classes.
所以这给了我们基本的C接口。如果你想表明您可以集成异常处理的一种方式更完整的示例,那么你可以尝试在github上我的code:的
So that gives us the basic C interface. If you want a more complete example showing one way that you can integrate exception handling, then you can try my code on github : https://gist.github.com/mikeando/5394166
有趣的部分现在已经确保您获得所有必需的C ++库链接到你更大的库正确。海湾合作委员会(或铛),这意味着刚刚在干嘛用G ++的最后链接阶段。
The fun part is now ensuring that you get all the required C++ libraries linked into you larger library correctly. For gcc (or clang) that means just doing the final link stage using g++.
这篇关于开发C封装API面向对象的C ++ code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!