开发者

Generator to change a C++ API into a C interface?

开发者 https://www.devze.com 2023-04-12 18:33 出处:网络
Is there some kind of tool i can give a c开发者_C百科++ header to and have it change the API/lib/interface into a C interface as well as generate the C functions to cast and call the C++ code?I think

Is there some kind of tool i can give a c开发者_C百科++ header to and have it change the API/lib/interface into a C interface as well as generate the C functions to cast and call the C++ code?


I think SWiG might do most of that.


I don't know of a tool that can do this automatically, it can get pretty tricky if you have classes as arguments to the public functions in your API.

But if your API is simple and mostly using native types, then you can do this by hand with not too much work. Here is a quick example of a C wrapper for a C++ class. Let's say this is the C++ class to wrap, let's call it test.h:

class Test {
public:
    Test();
    int do_something(char* arg);
    bool is_valid(); // optional, but recommended (see below)
};

This is your C header test_c.h:

typedef void* TestHandle;
TestHandle newTest();
int deleteTest(TestHandle h);
int Test_do_something(TestHandle h, char* arg);

And your C implementation will be a C++ file with C functions, let's say 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);
}   

The is_valid() method is there to guarantee that you were not given a bad handle. For example, you can store a magic number in all your instances, then is_valid() just ensures the magic number is there.

0

精彩评论

暂无评论...
验证码 换一张
取 消