• 23.windows库程序(三)


    1.动态库中的类

      (1)DLL中类的导出

         在类名称前添加 _declspec(dllexport),例如:

           class _declspec(dllexport) CMath{ ... };

         通常使用预编译开关切换类的导入导出定义,例如:

           #ifdef  DLLCLASS_EXPORT

           #define  EXT_CLASS  _declspec(dllexport)  //dll

           #else

           #define  EXT_CLASS  _declspec(dllimport)  //使用

           #endif

           class  EXT_CLASS  CMsth{ ... };

      (2)使用

         a.导入dll的lib

         b.类的定义

         c.使用类

      (3)动态库的程序入口

         入口程序不是dll必须的,常用于dll内部初始化或善后处理。

         BOOL  WINAPI  DllMain( HINSTANCE  hinstDll,      //动态库实例句柄

                      DWORD       fdwReason,     //被调用的原因

                                                 LPVOID        lpvReserved);  //保留值

         成功,返回TRUE,表示动态库加载成功。

         动态库的加载或卸载时会被调用。例如:在LoadLibrary和FreeLibrary时会被调用。

      相关代码:

      (1)库头文件 

    #ifndef DLLCLASS_H
    #define DLLCLASS_H
    
    #ifdef DLLCLASS_EXPORT
    #define EXT_CLASS _declspec(dllexport)
    #else
    #define EXT_CLASS _declspec(dllimport)
    #endif
    
    class EXT_CLASS CMath
    {
    public:
        int Add(int a, int b);
        int Sub(int a, int b);
    };
    
    #endif

      (2)库实现文件

    #define DLLCLASS_EXPORT
    #include "windows.h"
    #include "DllClass.h"
    #include "stdio.h"
    
    int CMath::Add(int a, int b)
    {
        return a + b;
    }
    
    int CMath::Sub(int a, int b)
    {
        return a - b;
    }
    
    BOOL CALLBACK DllMain(HINSTANCE hinstDll, DWORD fdwReasion, LPVOID pVoid)
    {
        switch (fdwReasion)
        {
        case DLL_PROCESS_ATTACH:
            //初始化工作
            printf("Loading...
    ");
            break;
        case DLL_PROCESS_DETACH:
            //善后处理
            printf("Unloading...
    ");
            break;
        }
        return TRUE;
    }

      (3)使用

    #include <iostream>
    #include "../DllClass/DllClass.h"
    
    #pragma comment(lib, "../Debug/DllClass.lib")
    
    int main()
    {
        CMath math;
        int sum = math.Add(5, 2);
        int sub = math.Sub(5, 2);
        std::cout << "sum=" << sum << std::endl << "sub=" << sub << std::endl;
        return 0;
    }

      运行结果:

      

  • 相关阅读:
    WSGI-mini-web框架服务器
    pymsql链接数据库报错2003的解决过程记录
    官方案例--Survival Shoot(一)
    Python-Day5修改haproxy配置文件
    Python-Day4实现简单的shell sed替换功能
    Python-列表嵌套字典-名片管理系统(适合刚学习完字典和列表的同学练手)
    Python-列表的运用-名字管理系统
    Vi 编写一个剪刀石头布游戏
    Python-Day3 购物系统
    Python-Day2三级菜单
  • 原文地址:https://www.cnblogs.com/csqtech/p/5660877.html
Copyright © 2020-2023  润新知