【发布时间】:2011-12-07 11:33:25
【问题描述】:
是否有某种工具可以提供 c++ 标头并将其更改 API/lib/interface 为 C 接口以及生成 C 函数以转换和调用 C++ 代码?
【问题讨论】:
是否有某种工具可以提供 c++ 标头并将其更改 API/lib/interface 为 C 接口以及生成 C 函数以转换和调用 C++ 代码?
【问题讨论】:
我认为SWiG 可能会完成大部分工作。
【讨论】:
我不知道有什么工具可以自动执行此操作,如果您将类作为 API 中公共函数的参数,它会变得非常棘手。
但是,如果您的 API 很简单并且主要使用原生类型,那么您可以手动完成此操作而无需太多工作。这是 C++ 类的 C 包装器的快速示例。假设这是要包装的 C++ 类,我们称之为test.h:
class Test {
public:
Test();
int do_something(char* arg);
bool is_valid(); // optional, but recommended (see below)
};
这是你的 C 头 test_c.h:
typedef void* TestHandle;
TestHandle newTest();
int deleteTest(TestHandle h);
int Test_do_something(TestHandle h, char* arg);
你的 C 实现将是一个带有 C 函数的 C++ 文件,比如说test_c.cpp:
extern "C" TestHandle newTest()
{
return (void*)new Test();
}
extern "C" int deleteTest(TestHandle h)
{
Test* this = static_cast<Test*>(h);
if (!this->is_valid())
return -1; // here we define -1 as "invalid handle" error
delete this;
return 0; // here we define 0 as the "ok" error code
}
extern "C" int Test_do_something(TestHandle h, char* arg)
{
Test* this = static_cast<Test*>(h);
if (!this->is_valid())
return -1; // here we define -1 as "invalid handle" error
return this->do_something(arg);
}
is_valid() 方法可以保证您没有得到错误的句柄。例如,您可以在所有实例中存储magic number,然后is_valid() 只是确保存在幻数。
【讨论】: