I'd like to create a C wrapper for a C++ library I wrote.
All the examples and SO's answers I found:
Using void, typedef void myhdl_t
Trojan horse structure: struct mather{ void *obj; };
# .h
struct mather;
typedef struct mather mather_t;
# .cpp
struct mather{
void *obj;
};
mather_t *mather_create(int start){
mather_t *m;
CPPMather *obj;
m = (typeof(m))malloc(sizeof(*m));
obj = new CPPMather(start);
m->obj = obj;
return m;
}
Deriving a struct from a C++ base class
# .h
struct Foo;
#.cpp
struct Foo : public FooInternal {
using FooInternal::FooInternal;
};
struct Foo* foo_new() {
try {
return new Foo;
} catch(...) {
return nullptr;
}
}
My case:
I'd like to have an allocation C function like that:
int alloc_function(struct Foo** foo){
if (foo==nullptr)
return -EFAULT; // The user gives nullptr
if (*foo!=nullptr)
return -EFAULT; // already allocated
// error: Incompatible pointer types assigning to 'struct Foo *' from 'Foo *'
*foo = new Foo;
// No error but Clang-Tidy: Do not use static_cast to downcast from a base to a derived class
*foo = static_cast<struct Foo*>(new Foo);
return 0;
}
I understand Clang-Tidy isn't a compiler error but I still would like to do it the right way.
- What's the best practice for writing a C-wrapper? Any real example?