c++ 动态链接库定义/显示使用

参考文档:https://www.cnblogs.com/sleepwalker/p/5016610.html

定义动态链接库函数(_stdcall 通用Pascal程序的缺省调用方式):

#include "stdafx.h"
#include <iostream>
using namespace std;

#define LIB_EXPORT 1
#if LIB_EXPORT
#define LIB_DLL extern "C" _declspec(dllexport)
#else
#define LIB_DLL extern "C" _declspec(dllimport)
#endif

//可以将声明和定义写在同一个位置上
LIB_DLL bool _stdcall can_test(std::string& sn,std::string& ipAddr, int& port)
{
	return false;
}

def文件的主要作用为解决使用stdcall方式后函数名被改变的问题。

LIBRARY
EXPORTS
can_test @ 1

C++显示调用dll方式

#include <Windows.h>
#include <iostream>

using namespace std;
int main(){

	//此处函数指针定义中 _stdcall 非常重要,若不加上这个的话,会导致程序崩溃
	typedef bool(_stdcall *pCanTest)(std::string&,std::string&,int&);
	HMODULE hDll=LoadLibrary("AtxSharedDll.dll");
	if(hDll!=NULL){
		pCanTest can=(pCanTest)GetProcAddress(hDll,"can_test");
		if(can!=NULL){
			string a="1234";
			string b="3456";
			int port=2345;
			std::cout<<can(a,b,port)<<std::endl;
		}
		else{
			std::cout<<"fail find func"<<std::endl;
		}
	}else{
		std::cout<<"fail load dll"<<std::endl;
	}
	FreeLibrary(hDll);
	getchar();
	return 0;
}

程序运行后截图:
run
另一种调用方式:_cdecl。
此方式是C/C++的默认调用方式,只需要将源文件中的_stdcall去掉即可,此方式也不需要.def文件,若只是给C/C++调用的,此方式更加简洁。

至此,C++动态链接库的定义和使用书写完毕。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值