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后结果如下

     

发布了63 篇原创文章 · 获赞 58 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/xinjiang666/article/details/105588518
今日推荐