调用不同dll中的同一函数
就是使用LoadLibrary取得相应的dll句柄,然后使用GetProcAddress取得相应函数接口的入口地址,
通过函数指针调用就行了。可以使用Dependency Walk 工具查看dll中有哪些接口。
我和我的组长各写了一个,高下立断。
主要我没有判断NULL值,需要注意。
我的代码:
1 class DX8Interface 2 { 3 typedef HRESULT (WINAPI * DX8_D3DXCreateSprite)(LPDIRECT3DDEVICE8, LPD3DXSPRITE *); 4 public: 5 static HRESULT WINAPI D3DXCreateSprite(LPDIRECT3DDEVICE8 pDevice, LPD3DXSPRITE* ppSprite); 6 static bool Initial(); 7 static bool Free(); 8 private: 9 static HMODULE m_hDX8Module; 10 static DX8_D3DXCreateSprite m_pfD3DXCreateSprite; 11 }; 12 DX8Interface::DX8_D3DXCreateSprite DX8Interface::m_pfD3DXCreateSprite = NULL; 13 HMODULE DX8Interface::m_hDX8Module = NULL; 14 HRESULT WINAPI DX8Interface::D3DXCreateSprite(LPDIRECT3DDEVICE8 pDevice, LPD3DXSPRITE* ppSprite) 15 { 16 if(NULL == m_pfD3DXCreateSprite) Initial(); 17 return m_pfD3DXCreateSprite(pDevice, ppSprite); 18 } 19 bool DX8Interface::Initial() 20 { 21 m_hDX8Module = ::LoadLibrary(_T("D3DX8ab.dll")); 22 m_pfD3DXCreateSprite = (DX8_D3DXCreateSprite)GetProcAddress(m_hDX8Module, "D3DXCreateSprite"); 23 24 return true; 25 } 26 bool DX8Interface::Free() 27 { 28 return ::FreeLibrary(m_hDX8Module); 29 }
leader代码:
1 class DX9Interface 2 { 3 typedef HRESULT (WINAPI *D3DXCreateSpriteFun)(LPDIRECT3DDEVICE9, LPD3DXSPRITE*); 4 public: 5 static bool Initial() 6 { 7 m_hModule = LoadLibrary(_T("D3dx9_42.dll")); 8 if(m_hModule == NULL) 9 { 10 TRACEE(_T("Load D3dx9_42.dll failed.")); 11 return false; 12 } 13 14 m_pD3DXCreateSprite = (D3DXCreateSpriteFun)GetProcAddress(m_hModule, "D3DXCreateSprite"); 15 if(m_pD3DXCreateSprite == NULL) 16 { 17 TRACEE(_T("Get D3DXCreateSpriteFun for D3dx9_42.dll failed.")); 18 return false; 19 } 20 21 return true; 22 } 23 24 static void Destory() 25 { 26 m_pD3DXCreateSprite = NULL; 27 28 if(m_hModule) 29 { 30 FreeLibrary(m_hModule); 31 m_hModule = NULL; 32 } 33 } 34 35 static HRESULT D3DXCreateSprite(LPDIRECT3DDEVICE9 pDevice, LPD3DXSPRITE* ppSprite) 36 { 37 if(m_pD3DXCreateSprite == NULL) 38 { 39 if(!Initial()) 40 { 41 return S_FALSE; 42 } 43 } 44 return m_pD3DXCreateSprite(pDevice, ppSprite); 45 } 46 private: 47 static HMODULE m_hModule; 48 static D3DXCreateSpriteFun m_pD3DXCreateSprite; 49 };