• C++ 生成 dll 和调用 dll 的方法实例(转)


    1)生成dll

    建立两个文件 xxx.h , xxx.cpp

    xxx.h内容如下:

    #ifdef BUILD_XXX_DLL
    #define EXPORT __declspec(dllexport)
    #else
    #define EXPORT __declspec(dllimport)
    #endif

    extern "C"{
    EXPORT void example(void);
    ... ...
    }

    xxx.cpp内容如下:

    #define BUILD_XXX_DLL
    #include "xxx.h"

    void example(void)
    {
    }
    ... ...

    然后从DOS控制台进行编译(假设已经安装mingw并加入环境变量)
    g++ -shared -Wl,--kill-at,--output-def,xxx.def -o xxx.dll xxx.cpp

    (因为C++通过修饰函数名来实现函数重载,所以我们要用extern "C"配合--kill-at编译选项来避免对函数名的修正,BUILD_XXX_DLL宏的作用是用来选择函数原型声明的作用)

    2)静态调用dll

    在新文件yyy.cpp里加入如下内容;
    #include "xxx.h"
    #pragma comment(lib,"xxx.dll")

    生成的dll不需要def文件和cpp文件也可以
    不包含xxx.h的话,需要把h文件内的函数原型声明添加进yyy.cpp

    编译时需要加入dll,类似这样:
    g++ -L. -o yyy.exe yyy.cpp xxx.dll

    3)动态调用dll

    首先,你需要包含windows.h
    #include <windows.h>

    你还需要一个句柄保存装入的dll文件
    HINSTANCE hDll=LoadLibrary("xxx.dll");

    声明所需函数的对应函数指针类型
    typedef void (*pfunc)(void);

    获得指向函数的函数指针
    pfunc pf=(pfunc*)GetProcAddress(hDll,"example");

    使用完毕后,要释放dll文件
    FreeLibrary(hDll);

  • 相关阅读:
    POJ 1113 Wall
    POJ 3525 Most Distant Point from the Sea
    POJ 3335 Rotating Scoreboard
    POJ 1228 Grandpa's Estate
    POJ 1873 The Fortified Forest
    POJ 2354 Titanic
    POJ 3130 How I Mathematician Wonder What You Are!
    POJ 1106 Transmitters
    POJ 1474 Video Surveillance
    seajs 的研究一 无题
  • 原文地址:https://www.cnblogs.com/blog-3123958139/p/5574348.html
Copyright © 2020-2023  润新知