Categories
api c c++ shared-libraries

C wrapper for C++ class with stack allocation

Let’s say we have a C++ library with a class like this:

class TheClass {
public:
TheClass() { ... }
void magic() { ... }
private:
int x;
}

Typical usage of this class would include stack allocation:

TheClass object;
object.magic();

We need to create a C wrapper for this class. The most common approach looks like this:

struct TheClassH;
extern "C" struct TheClassH* create_the_class() {
return reinterpret_cast<struct TheClassH*>(new TheClass());
}
extern "C" void the_class_magic(struct TheClassH* self) {
reinterpret_cast<TheClass*>(self)->magic();
}

However, it requires heap allocation, which is clearly not desired for such a small class.

I’m searching for an approach to allow stack allocation of this class from C code. Here is what I can think of:

struct TheClassW {
char space[SIZEOF_THECLASS];
}
void create_the_class(struct TheClassW* self) {
TheClass* cpp_self = reinterpret_cast<TheClass*>(self);
new(cpp_self) TheClass();
}
void the_class_magic(struct TheClassW* self) {
TheClass* cpp_self = reinterpret_cast<TheClass*>(self);
cpp_self->magic();
}

It’s hard to put real content of the class in the struct’s fields. We can’t just include C++ header because C wouldn’t understand it, so it would require us to write compatible C headers. And this is not always possible. I think C libraries don’t really need to care about content of structs.

Usage of this wrapper would look like this:

TheClassW object;
create_the_class(&object);
the_class_magic(&object);

Questions:

  • Does this approach have any dangers or drawbacks?
  • Is there an alternative approach?
  • Are there any existing wrappers that use this approach?