VS封装DLL并调用DLL

在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)运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值