title: Loading an EXE as a DLL, local vftable
body: <p>I have an exe named <code>test.exe</code> which is usually used as a stand-alone application. I want to use this exe as a module (a dll) inside another application, app.exe.</p>
  
  <p>The code in test.exe does something really simple like:</p>
  
  <pre><code>void doTest()
  {
      MyClass *inst = new MyClass();
      inst-&gt;someMethod();
  }
  </code></pre>
  
  <p>Where <code>someMethod()</code> is virtual and MyClass has a virtual d'tor.<br>
  <code>doTest()</code> is exported from test.exe and thus a lib called test.lib is created<br>
  app.exe is linked with this lib to statically load test.exe when it starts.</p>
  
  <p>When I'm running test.exe stand-alone it runs just fine but when I'm running it loaded from within app.exe it crashes.<br>
  Stepping into the code with the debugger revealed that the crash is in the call to the virtual method. It turns out that the vftable somehow goes bad.  </p>
  
  <p>After some investigations it turns out that when the code inside the constructor of MyClass is running , the vftable is one thing but when the call to <code>new</code> returns it is replace with something else called a "local vftable". I found <a href="http://groups.google.com/group/microsoft.public.vc.language/msg/55cdcefeaf770212" rel="nofollow noreferrer">this obscure discussion about why this is</a>.  </p>
  
  <p>After about a day of debugging it occurred to me that the pointers in this "local vftable" are the same in both cases, when test.exe is stand alone and whenit is loaded as a module. This can't be right because test.exe is loaded into a different address...<br>
  To test this theory I changed the loading address in the linker options to the one where test.exe is loaded when it is in app.exe and now, lo and behold, everything works.</p>
  
  <p>Obviously, this is not a permanent solution because next time this randomly selected address may be occupied and the same problem will occur again.</p>
  
  <p>So my question: Why is this "local vftable" tied to the static loading address of the exe? is loading an exe as a module a bad thing? why does the exe assume it is loaded to its static address?</p>
  
  <p>Just for context: this is all done with MSVC 2008, Windows XP x64.</p>