zoukankan      html  css  js  c++  java
  • C++ 动态链接库 DLL 的一些笔记

    DLL 文件源代码:

    // test.h
    #ifdef TEST_EXPORTS
    #define TEST_API __declspec(dllexport)
    #endif
    
    class TEST_API Test
    {
    public:
    	Test() {};
    	Test(const char* _name) {
    		name = _name;
    	};
    	virtual ~Test() {};
    	bool test();
    };
    
    // test.cpp
    #include "test.h"
    ...
    
    extern "C" TEST_API Test* get_instance(const char* _name) {
    	return new Test(_name); 
    }
    
    

    生成 DLL 文件 test.dll。

    windows下显式调用:

    #include "test.h"
    
    typedef Test*(*LPFNDLLFUNC1)(const char*);
    
    void main(){
        HMODULE hMod = LoadLibrary("test.dll");
        if (hMod == nullptr) {
    	return nullptr;
        }
        LPFNDLLFUNC1 get_instance = (LPFNDLLFUNC1)GetProcAddress(hMod, "get_instance");
        if (get_instance == nullptr) {
            FreeLibrary(hMod);
            return nullptr;
        }
        Test* test = get_instance("123");
        return 0;
    }
    

    注意调用的地方函数的声明要和函数在 DLL 里的一致。否则,会遇到如下报错:

    Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention.

    经过检查就是因为我原来在调用时的函数声明为:

    typedef Test*(CALLBACK *LPFNDLLFUNC1)(const char*);
    

    这里的CALLBACK 就是 __stdcall,而DLL中却不是:

    extern "C" TEST_API __stdcall Test* get_instance(const char* _name) {
    

    另外,不要用 STL 里的容器(vector、string 等)作为参数在 DLL 中传递,因为有可能在调用的地方申请内存,但释放是在 DLL 中,它就不知道正确的长度了。
    所以不要传 vector<type>
    可以传 const vector<type>vector<type>*

  • 相关阅读:
    特殊符号大全
    CSS速记
    JavaScript命名规范
    vim 常用快捷键
    Set a mouse hook
    ASP不可遗弃的通用函数
    ASP递归层级表格数据展示
    最简约JS日历控件
    ASP统计图
    ASP标准MD5代码
  • 原文地址:https://www.cnblogs.com/flipped/p/9147873.html
Copyright © 2011-2022 走看看