Can I get away with this C++ downcasting fib?
<p>I have a C library that has types like this:</p>

<pre><code>typedef struct {
  // ...
} mytype;

mytype *mytype_new() {
  mytype *t = malloc(sizeof(*t));
  // [Initialize t]
  return t;
}

void mytype_dosomething(mytype *t, int arg);
</code></pre>

<p>I want to provide C++ wrappers to provide a better syntax. However, I want to avoid the complication of having a separately-allocated wrapper object. I have a relatively complicated graph of objects whose memory-management is already more complicated than I would like (objects are refcounted in such a way that all reachable objects are kept alive). Also the C library will be calling back into C++ with pointers to this object and the cost of a new wrapper object to be constructed for each C->C++ callback (since C doesn't know about the wrappers) is unacceptable to me.</p>

<p>My general scheme is to do:</p>

<pre><code>class MyType : public mytype {
 public:
   static MyType* New() { return (MyType*)mytype_new(); }
   void DoSomething(int arg) { mytype_dosomething(this, arg); }
};
</code></pre>

<p>This will give C++ programmers nicer syntax:</p>

<pre><code>// C Usage:
mytype *t = mytype_new();
mytype_dosomething(t, arg);

// C++ Usage:
MyType *t = MyType::New();
t-&gt;DoSomething(arg);
</code></pre>

<p>The fib is that I'm downcasting a <code>mytype*</code> (which was allocated with <code>malloc()</code>) to a <code>MyType*</code>, which is a lie.  But if <code>MyType</code> has no members and no virtual functions, it seems like I should be able to depend on <code>sizeof(mytype) == sizeof(MyType)</code>, and besides <code>MyType</code> has no actual data to which the compiler could generate any kind of reference.</p>

<p>So even though this probably violates the C++ standard, I'm tempted to think that I can get away with this, even across a wide array of compilers and platforms.</p>

<p>My questions are:</p>

<ol>
<li>Is it possible that, by some streak of luck, this does not actually violate the C++ standard?</li>
<li>Can anyone think of any kind of real-world, practical problem I could run into by using a scheme like this?</li>
</ol>

<p>EDIT: @James McNellis asks a good question of why I can't define MyType as:</p>

<pre><code>class MyType {
 public:
  MyType() { mytype_init(this); }
 private:
  mytype t;
};
</code></pre>

<p>The reason is that I have C callbacks that will call back into C++ with a <code>mytype*</code>, and I want to be able convert this directly into a <code>MyType*</code> without having to copy.</p>
