首先,我创建一个名为SimpleDll.dll
的简单dll,其头文件:
// SimpleDll.h
#ifdef MYLIBAPI
#else
#define MYLIBAPI __declspec(dllimport)
#endif
MYLIBAPI int Add(int a. int b);
其源代码:
// SimpleDll.c
#include <windows.h>
#define MYLIBAPI __declspec(dllexport)
#include "SimpleDll.h"
int Add(int a, int b)
{
return a + b;
}
然后我在另一个项目中调用它,它工作正常:
// TestSimpleDll.c
#include "stdafx.h"
#include <windows.h>
#include "SimpleDll.h"
#pragma comment(lib, "SimpleDll.lib")
int _tmain(int argc, _TCHAR* argv[])
{
printf("%d", Add(10, 30)); // Give the expected result 40
return 0;
}
但是,当我调用 GetProcAddress
来获取它的地址时,它不起作用!
// TestSimpleDll2.c
#include "stdafx.h"
#include <windows.h>
#include "SimpleDll.h"
#pragma comment(lib, "SimpleDll.lib")
int _tmain(int argc, _TCHAR* argv[])
{
printf("%d", Add(10, 30)); // Give the expected result 40
HMODULE hModule = GetModuleHandleA("SimpleDll.dll"); // hModule is found
PROC add_proc = GetProcAddress(hModule, "Add"); // but Add is not found !
// add_proc is NULL!
return 0;
}
感谢您的帮助。 (PS:我在Windows7上使用VS2010)
更新:
这是 depedency walker 为 SimpleDll.dll
文件显示的内容:
最佳答案
如果您想导出 GetProcAddress 的名称,您应该使用 .def 文件。否则你将不得不处理 c++ 名称 mangling并带有符号装饰。
您可以通过将函数声明为 extern "C"
来避免修饰,但避免修饰的唯一方法是使用 .DEF 文件。
还有一件事 - 在 Dependency walker 中 - 使用 F10 在修饰名和未修饰名之间切换。
关于c++ - 为什么 GetProcAddress 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5684737/