C++:VS2017 C++ 生成dll并调用 示例

一、生成dll

1.1 新建项目

项目类型为“动态链接库(DLL)”,名称为“xj”;Release,x64

1.2 添加头文件“xj.h”

1.3 修改属性

右击项目—配置属性—C/C++—预编译头—不使用预编译头

1.4 示例

1.4.1 示例1:整数相加的函数

1.4.2 示例2:利用OpenCV读取图片高和宽的函数(可忽略)

(需添加包含目录和附加依赖项,如下)

分享给有需要的人,代码质量勿喷

1.4.3 xj.h

#ifndef XJ
#define XJ

//system
#include <iostream>

//openCV
#include "opencv2/opencv.hpp"


extern "C" _declspec(dllexport) int xjTestAdd(const int &a, const int &b);
extern "C" _declspec(dllexport) void xjTestReadImage(const std::string &imgPath, int &width, int &height);

#endif // !XJ

1.4.4 xj.cpp

#include "xj.h"

int xjTestAdd(const int &a, const int &b)
{
	return a + b;
}

void xjTestReadImage(const std::string &imgPath, int &width, int &height)
{
	cv::Mat img = cv::imread(imgPath);
	width = img.cols;
	height = img.rows;
}

1.5 生成dll

右击解决方案——重新生成,成功即可生成“xj.dll”

二、调用dll

2.1 新建项目

新建“Windows控制台应用程序”,名称为“xjTest” ;Release,x64,先生成一下

2.2 复制dll

将F:\xj\x64\Release\xj.dll 复制到 F:\xjTest\x64\Release文件夹中

2.3 xjTest.cpp

#include "pch.h"
#include <iostream>

//system
#include <Windows.h>

//local
typedef int(*xj_TestAdd)(const int &a, const int &b); // 声明
typedef void(*xj_TestReadImage)(const std::string &imgPath, int &width, int &height);
HMODULE hm = LoadLibrary(L"xj.dll"); // 引用dll


int main()
{
	if (hm != NULL)
	{
		int a = 11, b = 55;
		xj_TestAdd xjAdd = (xj_TestAdd)GetProcAddress(hm, "xjTestAdd");
		int sum = xjAdd(11, 55);
		std::cout << a << " + " << b << " = " << sum << std::endl << std::endl;

		std::string path = "F:/test.jpg";
		int width = -3, height = -3;
		xj_TestReadImage xjReadImage = (xj_TestReadImage)GetProcAddress(hm, "xjTestReadImage");
		xjReadImage(path, width, height);
		std::cout << "width = " << width << ", height = " << height << std::endl << std::endl;
	}
}

2.4 F5后结果如下

     

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

累了就要打游戏

把我养胖,搞代码

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值