問題描述
我希望開發(fā)一組 C API,這些 API 將環(huán)繞我們現(xiàn)有的 C++ API 以訪問我們的核心邏輯(用面向?qū)ο蟮?C++ 編寫).這本質(zhì)上是一個膠水 API,允許我們的 C++ 邏輯被其他語言使用.有哪些好的教程、書籍或最佳實踐介紹了將 C 封裝在面向?qū)ο蟮?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 代碼中啟用我們的 C++ 庫,因此 SWIG 沒有太大幫助.(好吧,也許 SWIG 可以用來做到這一點,但我不是 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)
我們最終做的就是:
- 每個對象都在 C 中傳遞一個不透明的句柄.
- 構(gòu)造函數(shù)和析構(gòu)函數(shù)被包裹在純函數(shù)中
- 成員函數(shù)是純函數(shù).
- 其他內(nèi)置函數(shù)盡可能映射到 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 );
接口的實現(xiàn)看起來像這樣(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);
}
}
我們從原始類派生我們的不透明句柄以避免需要任何強制轉(zhuǎn)換,并且 (這似乎不適用于我當前的編譯器).我們必須使句柄成為結(jié)構(gòu)體,因為 C 不支持類.
We derive our opaque handle from the original class to avoid needing any casting, and (This didn't seem to work with my current compiler). We have to make the handle a struct as C doesn't support classes.
這樣就為我們提供了基本的 C 接口.如果您想要一個更完整的示例來展示您可以集成異常處理的一種方式,那么您可以在 github 上嘗試我的代碼:https://gist.github.com/mikeando/5394166
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
現(xiàn)在有趣的部分是確保您將所有必需的 C++ 庫正確鏈接到更大的庫中.對于 gcc(或 clang),這意味著只使用 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++.
這篇關(guān)于為面向?qū)ο蟮?C++ 代碼開發(fā) C 包裝器 API的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!