title: Wrapping a DLL - Understanding why Import Fails
body: <p><strong>Background</strong></p>
  
  <p>I have an embedded system which runs an application originally written in C++ and compiled in Visual Studio, which results in a single executable and more than 30 DLLs. These libraries cannot be browsed in VS Object Browser or other tools such as P/Invoke Interop Assistant. </p>
  
  <p>Loading some of the DLLs in Dependency Walker shows that all of them are missing some dependencies deep in their dependency tree (<em>cdfview.dll</em>, <em>dwmapi.dll</em>, <em>w32topl.dll</em>, ...) but according to <a href="https://stackoverflow.com/questions/173433/how-to-fix-dwmapi-dll-delay-load-dependency-under-winxp">this question</a>, that is likely not an issue.</p>
  
  <p>I have <strong>some</strong> of the source code files, and <strong>all</strong> of the compiled DLLs. The application currently runs without issue, indicating there are no real dependency issues.</p>
  
  <p>I am trying to call some library functions and eventually make a wrapper using C#, but am unable to successfully import and call even the simplest of functions. I always receive the following error:</p>
  
  <blockquote>
    <p>Unable to load DLL 'dllName.dll': A dynamic link library (DLL)
    initialization routine failed. (Exception from HRESULT: 0x8007045A)</p>
  </blockquote>
  
  <p><strong>Sample Code [EDITED]</strong></p>
  
  <p>From the C++ source code header file I have the following declarations:</p>
  
  <pre><code>#define OB_API __declspec(dllexport) __cdecl 
  
  typedef unsigned long DWORD;  // From windef.h
  typedef DWORD OBSTATUS;
  
  OBSTATUS OB_API TestObj(void);
  </code></pre>
  
  <p>In the C++ source code file the following definition is given (which would seem to always return <strong>true</strong>):</p>
  
  <pre><code>BOOL WINAPI DllMain(HANDLE  /* hModule */, 
                        DWORD   ul_reason_for_call, 
                        LPVOID  /* lpReserved */
                        )
  {
      switch (ul_reason_for_call)
      {
      case DLL_PROCESS_ATTACH:
      case DLL_PROCESS_DETACH:
      case DLL_THREAD_ATTACH:
      case DLL_THREAD_DETACH:
          break;
      }
      return TRUE;
  }
  </code></pre>
  
  <p>In my C# application class, I add the following declaration:</p>
  
  <pre><code>[DllImport(@"dllName.dll", CallingConvention=CallingConvention.Cdecl)
  public static extern ulong TestObj();
  </code></pre>
  
  <p>The DLL and C# application binary reside in the same directory.</p>
  
  <p><strong>Questions</strong></p>
  
  <p>From researching the error, it seems there is a large number of reasons this particular exception could be thrown and I was wondering how I could further troubleshoot this type of issue.</p>
  
  <p>Is there any way to get more detailed information on why the initialization routine failed?</p>
  
  <p><em>(Note: target system is running .NET framework 2.0)</em></p>