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後結果如下

     

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章