如何調用DLL中的導出類
阿新 • • 發佈:2018-02-11
too mod iostream processor ring 種類型 .net type copyto
之前在網上一直查不到關於把類打包成dll文件的程序,今天自己寫了個測試程序,供大家參考
一、生成類的dll文件
1.我是在vs2008上測試的,建立工程,在選擇建立何種類型的工程的時候,勾上application type中的dll;
2.添加一個頭文件,命名為mydll.h,這個頭文件就是我們測試時候要用接口文件,代碼如下:
[cpp] view plain copy
- #ifndef _MYDLL_H_
- #define _MYDLL_H_
- #ifdef MYLIBDLL
- #define MYLIBDLL extern "C" _declspec(dllimport)
- #else
- #define MYLIBDLL extern "C" _declspec(dllexport)
- #endif
- class _declspec(dllexport) testDll{//關鍵在這個地方,如果這個地方出錯,你所建立的dll文件也就不能用了
- private:
- int a;
- public:
- testDll();
- void setA();
- int getA();
- };
- #endif
3.添加一個源文件,命名為mydll.cpp,這個是類的實現文件:
[cpp] view plain copy
- #include "stdafx.h"
- #include <iostream>
- #include "mydll.h"
- using namespace std;
- testDll::testDll(){
- cout<<"test dll"<<endl;
- a = 11;
- }
- int testDll::getA()
- {
- return a;
- }
- void testDll::setA(){
- a = 33;
- }
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
- #pragma comment(lib, "dllOne.lib")
- #include "stdafx.h"
- #include <iostream>
- #include "mydll.h"
- using namespace std;
- int _tmain(int argc, _TCHAR* argv[])
- {
- testDll* tmp = new testDll();
- cout<<tmp->getA()<<endl;
- tmp->setA();
- cout<<tmp->getA()<<endl;
- getchar();
- return 0;
- }
4,運行,測試下。
如何調用DLL中的導出類