C++ 动态链接库的动态加载问题

1、如何使用显示加载动态链接库

加载方法:

  1. LoadLibrary
  2. GetProcAddress
  3. FreeLibrary

#include <iostream>
#include <Windows.h>
using namespace std;
#pragma comment(lib, "DllLoad.lib")
 
int main()
{
	HINSTANCE h = LoadLibraryA("DllLoad.dll");
	typedef int(*FunPtr)(int a, int b);//定义函数指针
	if (h == NULL)
	{
		FreeLibrary(h);
		printf("load lib error\n");
	}
	else
	{
		FunPtr funPtr = (FunPtr)GetProcAddress(h, "add");
		if (funPtr != NULL)
		{
			int result = funPtr(8, 3);
			printf("8 + 3 =%d\n", result);
		}
		else
		{
			printf("get process error\n");
			printf("%d", GetLastError());
		}
		FreeLibrary(h);
	}
	return 0;
}

2、GetProcAddress 出错,返回NULL(GetLastError返回:127—找不到指定的程序).

C++ 的name mangling,名字改编,导致名字不是fun,而是fun@@YAHXZ加上参数之类的,所以GetProcAddress 找不到函数地址。

解决:在dll中加入 extern “C” ,不使用名字改编:

extern "C" _declspec(dllexport) void Add(int a, int b);

猜你喜欢

转载自blog.csdn.net/mercy_ps/article/details/81214992