C/C++ 调用DLL

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

//dllExport.c

__declspec(dllexport)
int Add(int a, int b)
{
	return a + b;
}

//Visual Studio 2015 本机工具命令提示符:
//command:  cl /LDd dllExport.c

方法一: 

//dllImport.c

#include 

__declspec(dllimport) int Add(int a, int b);

int main()
{
	int ret = Add(10, 20);
	printf("%d\n", ret);
	return 0;
}

//Visual Studio 2015 本机工具命令提示符
//command:  cl /c dllImport.c
//command:  link dllImport.obj dllExport.lib
//command:  dllImport.exe
//output :  30

方法二:

//dllImport.c

#include 
#include 

typedef int (*Func)(int, int);

int main()
{
	Func func;

	//Load DLL
	HINSTANCE hInstance = LoadLibrary("dllExport.dll");
	if (hInstance == NULL)
	{
		printf("Error: unable to load DLL\n");
		return 1;
	}

	//Get function address
	func = (Func)GetProcAddress(hInstance, "Add");
	if (func == NULL)
	{
		printf("Error: unable to find DLL function\n");
		FreeLibrary(hInstance);
		return 1;
	}

	//Call function
	int ret = func(10,20);

	//Unload DLL file
	FreeLibrary(hInstance);

	//Display result;
	printf("Result = %d\n", ret);
	return 0;
}

//command: cl dllImport.c
//command: dllImport.exe
//output: Result = 30

 

转载于:https://my.oschina.net/tigerBin/blog/889530

你可能感兴趣的:(C/C++ 调用DLL)