• 如何调用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,运行,测试下。

  • 相关阅读:
    模拟赛20181101 雅礼 Wearry 施工 蔬菜 联盟
    模拟赛20181031 雅礼 Wearry 养花 折射 画作
    set/priority_queue的运算符重载
    set的完整用法
    最长公共上升子序列 O(n^2)
    无向图边双联通分量 tarjan 模板
    ID 迭代加深搜索 模板 埃及分数
    树上背包DP Luogu P2014 选课
    A* 第k短路
    [POJ3468]关于整数的简单题 (你想要的)树状数组区间修改区间查询
  • 原文地址:https://www.cnblogs.com/oneway1990/p/8440456.html
Copyright © 2020-2023  润新知