C wrapper for C++ class with stack allocation
<p>Let's say we have a C++ library with a class like this:</p>

<pre><code>class TheClass {
public:
  TheClass() { ... }
  void magic() { ... }
private:
  int x;
}
</code></pre>

<p>Typical usage of this class would include stack allocation:</p>

<pre><code>TheClass object;
object.magic();
</code></pre>

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

<pre><code>struct TheClassH;
extern "C" struct TheClassH* create_the_class() {
  return reinterpret_cast&lt;struct TheClassH*&gt;(new TheClass());
}
extern "C" void the_class_magic(struct TheClassH* self) {
  reinterpret_cast&lt;TheClass*&gt;(self)-&gt;magic();
}
</code></pre>

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

<p>I'm searching for an approach to allow stack allocation of this class from C code. Here is what I can think of:</p>

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

<p>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.</p>

<p>Usage of this wrapper would look like this:</p>

<pre><code>TheClassW object;
create_the_class(&amp;object);
the_class_magic(&amp;object);
</code></pre>

<p>Questions:</p>

<ul>
<li>Does this approach have any dangers or drawbacks?</li>
<li>Is there an alternative approach?</li>
<li>Are there any existing wrappers that use this approach?</li>
</ul>