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 {
TheClass() { ... }
void magic() { ... }
int x;

Typical usage of this class would include stack allocation:

TheClass object;

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) {

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);

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;


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