首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++ 动态链接库 DLL 的一些笔记

C++ 动态链接库 DLL 的一些笔记

作者头像
饶文津
发布2020-06-02 14:49:03
9460
发布2020-06-02 14:49:03
举报
文章被收录于专栏:饶文津的专栏饶文津的专栏

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-06-06 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档