1. 程式人生 > >如何調用DLL中的導出類

如何調用DLL中的導出類

too mod iostream processor ring 種類型 .net type copyto

之前在網上一直查不到關於把類打包成dll文件的程序,今天自己寫了個測試程序,供大家參考

一、生成類的dll文件

1.我是在vs2008上測試的,建立工程,在選擇建立何種類型的工程的時候,勾上application type中的dll;

2.添加一個頭文件,命名為mydll.h,這個頭文件就是我們測試時候要用接口文件,代碼如下:

[cpp] view plain copy
  1. #ifndef _MYDLL_H_
  2. #define _MYDLL_H_
  3. #ifdef MYLIBDLL
  4. #define MYLIBDLL extern "C" _declspec(dllimport)
  5. #else
  6. #define MYLIBDLL extern "C" _declspec(dllexport)
  7. #endif
  8. class _declspec(dllexport) testDll{//關鍵在這個地方,如果這個地方出錯,你所建立的dll文件也就不能用了
  9. private:
  10. int a;
  11. public:
  12. testDll();
  13. void setA();
  14. int getA();
  15. };
  16. #endif

3.添加一個源文件,命名為mydll.cpp,這個是類的實現文件:

[cpp] view plain copy
[cpp] view plain copy
  1. #include "stdafx.h"
  2. #include <iostream>
  3. #include "mydll.h"
  4. using namespace std;
  5. testDll::testDll(){
  6. cout<<"test dll"<<endl;
  7. a = 11;
  8. }
  9. int testDll::getA()
  10. {
  11. return a;
  12. }
  13. void testDll::setA(){
  14. a = 33;
  15. }

4.最後其他的文件都是vs2008自動生成的,不用去修改,現在編譯下,生成dll和lib文件;

二、測試自己生成的dll和lib文件

1、建立工程,在選擇建立exe應用程序類型;

2、把剛才生成的dll和lib文件拷到這個工程目錄下,另外把mydll.h也拷貝過來(關鍵);

3、忘了一點,在vs2008中,在linker中把dll 和lib的目錄加進去,還要把lib名字加入到addtional dependencies中;

4、在測試文件的主程序中添加如下代碼:

[cpp] view plain copy
  1. #pragma comment(lib, "dllOne.lib")
  2. #include "stdafx.h"
  3. #include <iostream>
  4. #include "mydll.h"
  5. using namespace std;
  6. int _tmain(int argc, _TCHAR* argv[])
  7. {
  8. testDll* tmp = new testDll();
  9. cout<<tmp->getA()<<endl;
  10. tmp->setA();
  11. cout<<tmp->getA()<<endl;
  12. getchar();
  13. return 0;
  14. }

4,運行,測試下。

如何調用DLL中的導出類