2012-02-10 20 views
2

我在Visual Studio 2010中有兩個項目。一個是簡單的(win32).exe項目,另一個是DLL項目。使用dll中的類函數

在我創建的DLL項目中只有一個簡單的類,只有一個方法。我想從我的EXE應用程序訪問這個類和方法。但我想訪問類,就好像它是自己的EXE項目的一部分,如:

CTest test = new CTest; 
test->TestMethod (); 

有沒有辦法做到這一點?就像釋放DLL的頭文件並在EXE項目的某處添加對DLL的引用或其他東西......?

+0

這可能有所幫助:[如何導出標準模板庫(STL)類的實例和包含作爲STL對象的數據成員的類](http://support.microsoft.com/kb/168958) – lsalamon 2012-02-10 23:58:06

+0

請參見[.Lib文件作爲鏈接器輸入](http://msdn.microsoft.com/en-us/library/ba1z7822.aspx) - 您的.dll項目生成.lib文件,並且.exe​​項目需要鏈接到。 – ildjarn 2012-02-11 00:13:27

回答

4

隨着@Luchian Grigore給出的建議,您需要在要從DLL加載的類上正確使用_declspec(dllimport)_declspec(dllexport)

在編譯使用DLL的可執行文件時編譯DLL和dllimport時使用dllexport。

--- CTest.h ---

#ifdef CTEST_EXPORT // You are compiling the DLL 
#define CTEST_DLL_EXPORT _declspec(dllexport) 
#else 
#define CTEST_DLL_EXPORT _declspec(dllimport) 
#endif 

class CTEST_DLL_EXPORT CTest 
{ 
public: 
    bool TestMethod(); 
}; 

--- CTest.cpp ---

#define CTEST_EXPORT 
bool CTest::TestMethod() 
{ 
    return(true); // Success? 
} 

--- --- main.cpp中

#include <iostream.h> // Whatever cin/cout are declared in... 
#include "CTest.h" 

int main() 
{ 
    CTest ct; 

    if(ct.TestMethod()) 
    { 
     cout << "Success" << endl; 
    } 
    else 
    { 
     cout << "Failure" << endl; 
    } 
    return(0); 
} 
1

包含標題並添加到額外的包含庫.lib生成的項目也生成.dll