title: C++ Loading a DLL into the default AppDomain
body: <p>Using my non-existent knowledge of C++ (hey, at least I know what a pointer is :P ), I managed to throw together some code samples to create a solution that will inject a DLL file into another program.</p>
  
  <p>Unfortunately, it's the DLL I'm INJECTING that's not working properly: it successfully displays the messageboxes (so I know the DLL is running), but it's not actually creating the instance of the specified type (from the managed DLL, which has a static constructor in type Injectee that writes to a file). So, can anyone help me with where I'm going wrong? (N.B. the managed DLL is the same .Net version, and installed to the GAC. There's also a copy in the same folder as the application I'm injecting into)</p>
  
  <p>This is the unmanaged injectee (that's supposed to load the managed DLL):</p>
  
  <pre><code>#include "stdafx.h"
  
  #include "Injectee.h"
  
  #include "stdafx.h"
  #include &lt;stdio.h&gt;
  #include "objbase.h"
  #include "MSCorEE.h"
  #import "C:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorlib.tlb" raw_interfaces_only
  using namespace mscorlib;
  
  void Bootstrap() {
      CoInitializeEx(0, COINIT_MULTITHREADED );
      ICorRuntimeHost* pICorRuntimeHost = 0;
      HRESULT st = CoCreateInstance(CLSID_CorRuntimeHost, 0, CLSCTX_ALL,
          IID_ICorRuntimeHost, (void**)&amp;pICorRuntimeHost);
      if(!pICorRuntimeHost) {
          MessageBox(NULL, TEXT("Failed at stage 1."), TEXT("Error"), MB_OK); 
      }
  
      HDOMAINENUM hEnum = NULL;
      pICorRuntimeHost-&gt;EnumDomains(&amp;hEnum);
  
      if(!hEnum) {
          MessageBox(NULL, TEXT("Failed at stage 2."), TEXT("Error"), MB_OK); 
      }
  
      IUnknown* pUunk = 0;
      st = pICorRuntimeHost-&gt;NextDomain(hEnum, &amp;pUunk);
      if(!pUunk) {
          MessageBox(NULL, TEXT("Failed at stage 3."), TEXT("Error"), MB_OK); 
      }
  
      _AppDomain * pCurDomain = NULL;
      st = pUunk-&gt;QueryInterface(__uuidof(_AppDomain), (VOID**)&amp;pCurDomain);
      if(!pCurDomain) {
          MessageBox(NULL, TEXT("Failed at stage 4."), TEXT("Error"), MB_OK); 
      }
  
      _bstr_t assemblyName = "ZAI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9db2aaea0fceabbb";
      _bstr_t typeName = "Injectee";
  
      _ObjectHandle* pObjectHandle = 0;
  
      MessageBox(NULL, TEXT("Loading DLL."), TEXT("Error"), MB_OK); 
  
      pCurDomain-&gt;CreateInstance(assemblyName, typeName, &amp;pObjectHandle);
  }
  </code></pre>
  
  <p>Any help?</p>
  
  <p>(Note, managed assembly is built against both architectures (target app is x64), has base namespace ZAI))</p>
  
  <p>Any advice is appreciated.</p>
  
  <p>(In case you're wondering, I'm trying to add an API to a freeware, closed-source .Net app)</p>