Monday, September 11, 2006

要如何讓 DLL 讀取其所在目錄的 INI 檔

之前在遇到此問題時,是以 GetCurrentDirectory 來處理,結果會有問題。因為執行時在 DLL 中呼叫此 API 會得到 EXE 檔的目錄,而非 DLL 檔的目錄。以下的程式碼可以解決這個問題:

// With STL string
#include

char szAppPath[MAX_PATH] = "";
std::string strAppDirectory;

::GetModuleFileName(0, szAppPath, sizeof(szAppPath) - 1);

// Extract directory
strAppDirectory = szAppPath;
strAppDirectory = strAppDirectory.substr(0, strAppDirectory.rfind("\\"));



// With CString
char szAppPath[MAX_PATH] = "";
CString strAppDirectory;

::GetModuleFileName(0, szAppPath, sizeof(szAppPath) - 1);

// Extract directory
strAppDirectory = szAppPath;
strAppDirectory = strAppDirectory.Left(strAppDirectory.ReverseFind('\\'));



// With standard string
char szAppPath[MAX_PATH] = "";
char szAppDirectory[MAX_PATH] = "";

::GetModuleFileName(0, szAppPath, sizeof(szAppPath) - 1);

// Extract directory
strncpy(szAppDirectory, szAppPath, strrchr(szAppPath, '\\') - szAppPath);
szAppDirectory[strlen(szAppDirectory)] = '\0';

0 Comments:

Post a Comment

<< Home