• VC DLL 动态链接库(三)


      DLL 导出变量

      DLL 定义的全局变量可以被调用的进程访问, DLL 也可以访问调用进程的全局数据, 我们来看看在应用工程中引用 DLL 中的变量

    // lib.h
    #ifnedef LIB_H
    #define LIB_H
    extern int dllGlobalVar;
    
    #endif
    // lib.cpp
    #include "lib.h"
    #inlclude <windows.h>
    
    int dllGlobalVar;
    
    BOOL APLENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved){
        switch(ul_reason_for_call){
            case DLL_PROCESS_ATTACH: dllGlobalVar = 100;break;
            caes DLL_THREAD_ATTACH:
            caes DLL_THREAD_DETACH:
            caes DLL_PROCESS_DETACH: break;
        }
        return TRUE;
    }
    // lib.def
    LIBRARY "dllTest"
    EXPORTS dllGlobalVar CONSTANT;
    GetGlobalVar

      从 lib.h 和 lib.cpp 中可以看出, 全局变量在 DLL 中定义和使用方法与一般程序设计是一样的。

      下面在主函数中引用 DLL 中定义的全局变量

    // test.cpp
    #include <iostream>
    #pragma comment(lib, "dllTest.lib")
    extern int dllGlobalVar;
    
    int main(){
        cout << *(int *)dllGlobalVar << endl;
        *(int *)dllGlobalVar = 1;
        cout << *(int *)dllGlobalVar << endl;
    
        return 0;
    }

      其中需要注意的是用 extern int dllGlobalVar; 导入的并不是 DLL 中全局变量本身, 而是其地址, 使用强制指针转换来使用 DLL 中的全局变量, 所以千万不要有像这样的操作:dllGlobalVar = 1;

      这改变了指针的值, 以后再也引用不到 DLL 中的全局变量了。

      而还有一种更好的方法:

    // test.cpp
    #include <iostream>
    #pragma comment(lib, "dllTest.lib")
    extern int _declspec(dllimport) dllGlobalVar; // 用 _declspec(dllimport) 导入
    
    int main(){
        cout << *(int *)dllGlobalVar << endl;
        dllGlobalVar = 1; // 这里就可以直接使用, 无需强制指针转换
        cout << *(int *)dllGlobalVar << endl;
    
        return 0;
    }

      通过 _declspec(dllimport) 导入的就是 DLL 中的全局变量本身而不是其地址了。

    转载请注明出处:http://www.cnblogs.com/ygdblogs
  • 相关阅读:
    正则表达式
    JavaScript基础
    Servlet监听器
    Java EKT关键技术强化 tomcat中文乱码问题
    spring和springmvc 整合步骤
    [ERROR] [ERROR] Some problems were encountered while processing the POMs: [ERROR] 'packaging' with value 'war' is invalid. Aggregator projects require 'pom' as packaging. @ line 9, column 16
    Pagehelper的 使用
    异步 json的使用
    分页技术 PageHelper
    Exception encountered during context initialization
  • 原文地址:https://www.cnblogs.com/ygdblogs/p/5382699.html
Copyright © 2020-2023  润新知