在EXE和DLL中,FindResource的区别
以下的代码在EXE中,执行无误。可是在DLL中FindResource返回的值就为0了,我用::GetLastError(),得出的值是1813,也就是取不到资源,这是为什么?
- BOOL ExtractFile(char *szZlibFile,DWORD dwRID)
- {
- HANDLE hFile = NULL ;
- HRSRC hRsrc = NULL ;
- HGLOBAL hGlobal = NULL ;
-
- DWORD dwResSize = 0, dwBytesWrite = 0, dwBytesRead = 0;
- PVOID pRsrc = NULL, pConfigEncrypt = NULL;
- hRsrc = FindResource( NULL, MAKEINTRESOURCE(dwRID), "ZLIB");
- if(hRsrc == NULL)
- {
- MyDbgPrint("[ExtractFile] Locate Resource Error: %d\n", GetLastError());
- return FALSE;
- }
-
- dwResSize = SizeofResource(NULL, hRsrc);
-
- hGlobal = LoadResource(NULL, hRsrc);
- if(hGlobal == NULL)
- {
- MyDbgPrint("[ExtractFile] Load Resource Error: %d\n", GetLastError());
- return FALSE;
- }
-
- pRsrc = LockResource(hGlobal);
-
- hFile = CreateFile( szZlibFile , GENERIC_ALL, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
- if(hFile == INVALID_HANDLE_VALUE)
- {
- MyDbgPrint("[ExtractFile] Create %s File Error: %d\n", szZlibFile , GetLastError());
- return FALSE;
- }
-
- if( WriteFile( hFile, pRsrc, dwResSize, &dwBytesWrite, NULL) == FALSE)
- {
- MyDbgPrint("[ExtractFile] Write %s File Error: %d\n", szZlibFile , GetLastError());
- return FALSE;
- }
- CloseHandle(hFile);
- MyDbgPrint("[ExtractFile] Write %s File Success\n",szZlibFile);
- return TRUE;
-
- }
问题出在FindResource的第一个参数取得的HINSTANCE句柄是EXE的HINSTANCE句柄,自然在其中也找不到在DLL中引入的ZLIB这个位图ID了.同时SizeofResource,LoadResource中的第一个参数也应该是DLL的句柄.
解决方法如下:
- <span style="font-size:18px;">BOOL ExtractFile(char *szZlibFile,DWORD dwRID)
-
- {
-
- HANDLE hFile = NULL ;
-
- HRSRC hRsrc = NULL ;
-
- HGLOBAL hGlobal = NULL ;
-
- DWORD dwResSize = 0, dwBytesWrite = 0, dwBytesRead = 0;
-
- PVOID pRsrc = NULL, pConfigEncrypt = NULL;
-
- HINSTANCE hInst = GetModuleHandle( dll的路径 );
-
- hRsrc = FindResource( hInst , MAKEINTRESOURCE(dwRID), (LPCTSTR)"ZLIB");
-
- if(hRsrc == NULL)
-
- {
-
- return FALSE;
-
- }
-
- dwResSize = SizeofResource( hInst , hRsrc);
-
- hGlobal = LoadResource( hInst , hRsrc);
-
- if(hGlobal == NULL)
-
- {
-
- return FALSE;
-
- }
-
- pRsrc = LockResource(hGlobal);
-
- hFile = CreateFile( szZlibFile , GENERIC_ALL, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
-
- if(hFile == INVALID_HANDLE_VALUE)
-
- {
-
- return FALSE;
-
- }
-
- if( WriteFile( hFile, pRsrc, dwResSize, &dwBytesWrite, NULL) == FALSE)
-
- {
-
- return FALSE;
-
- }
-
- CloseHandle(hFile);
-
- return TRUE;
-
- }</span>
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。