如何调用DLL中的导出类

之前在网上一直查不到关于把类打包成dll文件的程序,今天自己写了个测试程序,供大家参考

一、生成类的dll文件

1.我是在vs2008上测试的,建立工程,在选择建立何种类型的工程的时候,勾上application type中的dll;

2.添加一个头文件,命名为mydll.h,这个头文件就是我们测试时候要用接口文件,代码如下:

 

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

3.添加一个源文件,命名为mydll.cpp,这个是类的实现文件:

 

 

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

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.   
  6. using namespace std;  
  7.   
  8. int _tmain(int argc, _TCHAR* argv[])  
  9. {  
  10.     testDll* tmp = new testDll();  
  11.     cout<<tmp->getA()<<endl;  
  12.     tmp->setA();  
  13.     cout<<tmp->getA()<<endl;  
  14.     getchar();  
  15.     return 0;  
  16. }  

4,运行,测试下。

转载于:https://www.cnblogs.com/oneway1990/p/8440456.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值