在VS中封装DLL,并调用DLL。
第一步:建立DLL工程
(1)建立工程名为exampleDLL的工程
(2)在exampleDLL.cpp输入以下代码
注:在要导出的变量前加extern _declspec(dllexport),在要导出的函数前加extern "C" _declspec(dllexport)。
// exampleDLL.cpp : 定义 DLL 应用程序的导出函数。
#include "stdafx.h"
extern _declspec(dllexport) int summ = 0;//必须初始化
extern _declspec(dllexport) int subb = 0;//必须初始化
//加法
extern "C" _declspec(dllexport) void mySum(int a, int b) {
summ = a + b;
}
//减法
extern "C" _declspec(dllexport) void mySub(int a,int b) {
subb = a - b;
}
//乘法
extern "C" _declspec(dllexport) double myMuti(double a, double b) {
return a * b;
}
(3)建立Source.def文件
①工程 -> 添加 -> 新建项 -> 代码
②在Source.def中输入以下代码
注:summ DATA和subb DATA是要封装的变量,mySum、mySub和myMuti是要封装的函数。
LIBRARY "exampleDLL"
EXPORTS
summ DATA;
subb DATA;
mySum;
mySub;
myMuti;
(4)不要直接运行程序,要点击生成 -> 生成解决方案,最后就会生成一个DLL文件。
第二步:建立exampleDLLTest工程
(1)在exampleDLLTest.cpp输入以下代码
#include <stdio.h>
#include <iostream>
#include <Windows.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
using namespace std;
int main()
{
HINSTANCE hInst = LoadLibrary(L"E:\\Code\\example\\exampleDLL\\x64\\Release\\exampleDLL.dll");
if (!hInst)
{
printf("加载dll失败!\n");
}
typedef void(_cdecl *mySumT)(int a, int b);
mySumT mySumD = (mySumT)GetProcAddress(hInst, "mySum");
mySumD(10,3);
int sumD = *(int*)GetProcAddress(hInst, "summ");
cout <<"summ=" << sumD << endl;
typedef void(_cdecl *mySubT)(int a, int b);
mySubT mySubD = (mySubT)GetProcAddress(hInst, "mySub");
mySubD(10, 3);
int subD = *(int*)GetProcAddress(hInst, "subb");
cout << "subb=" << subD << endl;
typedef double(_cdecl *myMutiT)(double a, double b);
myMutiT myMutiD = (myMutiT)GetProcAddress(hInst, "myMuti");
double mutii = myMutiD(10, 3);
cout << "mutii=" << mutii << endl;
::FreeLibrary(hInst);
system("pause");
return 0;
}
(2)运行结果