title: Delphi DllMain DLL_PROCESS_DETACH called before DLL_PROCESS_ATTACH
body: <p>I'm having a lot of trouble dealing with a DLL I've written in Delphi. I've set up a DllMain function using the following code in the library:</p>
  
  <pre><code>begin
    DllProc := DllMain;
  end.
  </code></pre>
  
  <p>My <code>DllMain</code> procedure looks like this:</p>
  
  <pre><code>procedure DllMain(reason: Integer);
  begin
    if reason = DLL_PROCESS_DETACH then
      OutputDebugString('DLL PROCESS DETACH')
    else if reason = DLL_PROCESS_ATTACH then
      OutputDebugString('DLL PROCESS ATTACH')
    else if reason = DLL_THREAD_ATTACH then
      OutputDebugString('DLL THREAD ATTACH')
    else if reason = DLL_THREAD_DETACH then
      OutputDebugString('DLL THREAD DETACH')
    else
      OutputDebugString('DllMain');
  end;
  </code></pre>
  
  <p>What I'm finding is that DETACH seems to be called (twice?!) by a caller (that I don't control) before ATTACH is ever called. Is that even possible, or am I misunderstanding how this is supposed to work? My expectation would be that every ATTACH call would be met with a matching DETACH call, but that doesn't appear to be the case.</p>
  
  <p>What's goin' on here?!</p>