[轉載]BCB:Put DLL File into EXE File


ref


BCB:Put DLL File into EXE File

把 DLL File 存放於應用程式裡,在應用程式是很常用的技巧,這個方法可以讓程式設計者只需給使用者一個執行檔就可以,不需再給DLL File。就不需要擔心使用者忘了把應用程式 和 DLL File 放在同一個目錄之下。有些程式設計者會使用InstallShield 把應用程式和DLL整合在一起來解決這個問題,而我們是把DLL放到執行檔的資源裡。

在PE格式的執行檔包含了資源,CODE 和 DATA,其中資源可以是文字(EX:版權宣告),圖片,ICON,動畫及二進制檔,我們就是把 DLL FILE 或者 DRIVER 宣告成二進制檔放到執行檔的資源中。

1.下載免費軟體 ResEdit
1-1. 開啟 ResEdit 選擇 File-> New project -> Resource Script File Name (.RC)
1-2. 在 Resources 欄位中,選擇 Add Resources ... -> User Defined -> Name identifier -> 輸入 RCDATA -> 選擇你的 DLL File.
1-3. 選擇檔案儲存,一共會有二個檔案,一個為 Resource.h 及 .RC FILE。

2. 打開 BCB 並開啟你的專案,選擇 View/Project Manager 開啟Project Manager DIALOG,將 .RC File 加入到你的專案中

在 Unit1.cpp 中,加入以下的程式碼
#include "resource.h"

typedef int (*GETNAME)(void); // DLL Function Name

void __fastcall TForm1::Button2Click(TObject *Sender) 
{
  HINSTANCE hinstApp;
  hinstApp=LoadLibrary(ExtractFileName(Application->ExeName).c_str());
  if(hinstApp!=NULL) {
      TResourceStream *rcStream=new
      TResourceStream ((int)hinstApp,IDR_RCDATA1,  RT_RCDATA);
      rcStream->SaveToFile("Naming.dll");
      HINSTANCE hinstDll;
      hinstDll=LoadLibrary("Naming.dll");
      if(hinstDll!=NULL) {
          GETNAME getName;
          int NameId=0;
          getName=(GETNAME)GetProcAddress(hinstDll,"_getName");
          if(getName!=NULL) {
              NameId=getName();
              ShowMessage(IntToStr(NameId));
          }
          FreeLibrary(hinstDll);
     }
     delete rcStream;
     FreeLibrary(hinstApp);
 }
}

虹光大成就-密教灌頂(一)