title: Self-Extracting Executable C++
body: <p>I am trying to understand how self-extracting PE files work. Can somebody explain why my code isn't working, or fix the main() part.</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;Windows.h&gt;
  
  using namespace std;
  
  void ExtractResource(const HINSTANCE hInstance, WORD resourceID, const char* outputFilename);
  
  int main()
  {
      HINSTANCE hInst = GetModuleHandle (0);
      ExtractResource(hInst, 101, "101.dll");
      ExtractResource(hInst, 102, "102.dll");
      ExtractResource(hInst, 103, "103.dll");
      ExtractResource(hInst, 104, "104.dll");
      cout &lt;&lt; "Files are now extracted!";
      Sleep(INFINITE);
  }
  
  
  void ExtractResource(const HINSTANCE hInstance, WORD resourceID, const char* outputFilename){
  
          // First find and load the required resource          
  
          HRSRC hResource = FindResource(hInstance, MAKEINTRESOURCE(resourceID), "BINARY");
  
          if(hResource==NULL)
  
                  return;
  
          HGLOBAL hFileResource = LoadResource(hInstance, hResource);
  
  
  
          // Now open and map this to a disk file          
  
          LPVOID lpFile = LockResource(hFileResource);          
  
          DWORD dwSize = SizeofResource(hInstance, hResource);            
  
  
  
          // Open the file and filemap          
  
          HANDLE hFile = CreateFileA(outputFilename, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_NEW,
  
                  FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_READONLY, NULL);          
  
          HANDLE hFilemap = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, dwSize, NULL);            
  
          LPVOID lpBaseAddress = MapViewOfFile(hFilemap, FILE_MAP_WRITE, 0, 0, 0);            
  
  
  
          // Write the file
  
          CopyMemory(lpBaseAddress, lpFile, dwSize);            
  
  
  
          // Unmap the file and close the handles
  
          UnmapViewOfFile(lpBaseAddress);
  
          CloseHandle(hFilemap);
  
          CloseHandle(hFile);
  
  }
  </code></pre>
  
  <p>I have 4 dll-files in resources, but I can't extract them using this. The resource ID´s should be correct, I checked it from resource header.</p>
  
  <p>Is the problem in <code>hInst</code> or what else there could be wrong? I hope somebody could help me :) I have just a ~month ago started learning C &amp; C++ so forgive me. </p>