2017-06-15 78 views
0

我想創建一個動態庫,並將其導入到我的主程序中。 但是我不能正確運行我的程序,因爲我從LIB切換到DLL。鏈接DLL和類方法明確

這是我的DLL .h文件中:

class Connector 
{ 
public: 
    Connector(std::string _apiKey, 
       std::string _masterCode, 
       std::string _masterSystem, 
       std::string _masterVersion, 
       int INTERNAL_PARAMETER = -1); 
    virtual ~Connector(); 
    std::string query(std::string method, 
         std::map<std::string, 
         std::string> params); 
    [...] 
} 

這是我mainApp鏈接代碼:

typedef std::string (CALLBACK* kcDLLFUNC_QUERY)(
     std::string, std::map<std::string, std::string>, std::string); 

HINSTANCE kcDLL = LoadLibrary(_T("Connect")); 
kcDLLFUNC_QUERY kcDLLFUNC_query = (kcDLLFUNC_QUERY)GetProcAddress(kcDLL, "query"); 

std::map<std::string, std::string> params; 
params["amount"] = "50"; 
std::string RES = kcDLLFUNC_query("de", params, ""); 
std::cout << RES << std::endl; 
FreeLibrary(kcDLL); 

沒有忘記什麼了嗎?

回答

1

主要問題是GetProcAddress()只適用於extern "C"函數。您要調用的函數是類的成員,並且您尚未導出函數或整個類。

我通常通過向DLL項目添加一個定義來實現此目的,然後在DLL項目中創建一個標頭,該標頭定義了一個指示函數/類是否被導出或導出的宏。事情是這樣的:

// Assumes IS_DLL is defined somewhere in the project for your DLL 
// (such as in the project's Properties: C/C++ -> Preprocessor) 
#ifdef IS_DLL 
    #define DLL_API __declspec(dllexport) 
#else 
    #define DLL_API __declspec(dllimport) 
#endif 

然後修改你的類是這樣的:

#include "DllExport.h" // name of the header file defined above 

class DLL_API Connector 
{ 
public: 
    Connector(std::string _apiKey, std::string _masterCode, std::string _masterSystem, std::string _masterVersion, int INTERNAL_PARAMETER = -1); 
    virtual ~Connector(); 
    std::string query(std::string method, std::map<std::string, std::string> params); 
    [...] 
} 

在您的.exe,包括對你的類的頭,並使用它像往常一樣。您還需要鏈接到DLL。在Visual Studio的最新版本中,按如下方式完成:

  1. 在解決方案資源管理器中,展開.exe的項目。
  2. 右鍵單擊References,然後選擇Add Reference...
  3. 在對話框中,在左側的列表中選擇Solution
  4. 選中DLL項目旁邊的複選框,然後按OK。

如果最終爲您的程序創建多個DLL,您需要更改定義的名稱以避免衝突(我通常在每個定義的名稱中包含DLL的名稱) 。

+0

我該如何切換DLL_API的定義?當我嘗試它時,我得到一些未解析令牌 –

+0

'DLL_API'因爲它將被定義爲DLL項目中的所有文件,並且不會爲EXE項目中的文件定義。我忘了提到的一個步驟是EXE項目必須鏈接到DLL的項目。我將通過如何添加參考來更新我的答案。 – Andy

+0

我試過了,效果很好!但我需要.lib文件來做到這一點。有沒有.lib文件鏈接的方法? –