至此,我们已经弄明白了如何从DLL里面将函数导出来,效果如下:

Here is the question:如何在自定义的子函数里面去使用导出的函数呢?

其实,解决的方法很简单,我们把函数类型设置为全局的,然后在需要使用导出函数的地方传入一个函数类型的指针

int  testDllFunc(addFunc thisadd)
{
   
	int a = 4, b = 5;
	int  c;
	thisadd(a, b, c);
	return c;
}

例如,我要在testDllFunc 里面调用我刚刚导出的add函数,那么,我在定义的时候,定义一个形参函数指针;

	int d = testDllFunc(add);
	cout << d;

然后,调用的时候,把刚刚导出的函数指针作为参数传进去;


#include<Windows.h> 
#include<iostream>
using namespace std;

#include <cuda_runtime.h> 
#include "device_launch_parameters.h" 


typedef int(*addFunc)(int&, int&, int&); // 定义函数指针类型


int  testDllFunc(addFunc thisadd)
{
   
	int a = 4, b = 5;
	int  c;
	thisadd(a, b, c);
	return c;
}


int main()
{
   
	/**************************************************************************************/
	//加载dll
	HMODULE module = LoadLibrary(TEXT("..\\x64\\Debug\\ArrayAddGenerate.dll"));
	if (module == NULL)
	{
   
		cout << "load dll error!" << endl;
		FreeLibrary(module);
		return 1;
	}
	/**************************************************************************************/
	//从dll中导出函数地址
	addFunc add;
	add = (addFunc)GetProcAddress(module, "add");
	GetLastError();
	if (add == NULL)
	{
   
		cout << "get dll error!" << endl;
		FreeLibrary(module);
		return 1;
	}
	//test
	int aa = 1;
	int bb = 2;
	int cc = 0;
	cout << cc << endl;
	add(aa,bb,cc);
	cout << cc << endl;
	/**************************************************************************************/
	int d = testDllFunc(add);
	cout << d;
	/**************************************************************************************/
	//从dll中导出函数地址
	typedef void(*ShowDevicePropFunc)(); // 定义函数指针类型
	ShowDevicePropFunc ShowDeviceProp;
	ShowDeviceProp = (ShowDevicePropFunc)GetProcAddress(module, "ShowDeviceProp");
	GetLastError();
	if (ShowDeviceProp == NULL)
	{
   
		cout << "get dll error!" << endl;
		FreeLibrary(module);
		return 1;
	}
	//test
	ShowDeviceProp();
	return 0;
}