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>*

转载于:https://www.cnblogs.com/flipped/p/9147873.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值