为什么GetProcAddress不起作用?

won*_*ng2 5 c++ windows winapi visual-studio name-decoration

首先,我创建一个名为的简单dll SimpleDll.dll,其头文件:

// SimpleDll.h
#ifdef MYLIBAPI
#else
#define MYLIBAPI __declspec(dllimport)
#endif

MYLIBAPI int Add(int a. int b);
Run Code Online (Sandbox Code Playgroud)

其源代码:

// SimpleDll.c
#include <windows.h>

#define MYLIBAPI __declspec(dllexport)
#include "SimpleDll.h"    

int Add(int a, int b)
{
    return a + b;
}
Run Code Online (Sandbox Code Playgroud)

然后我在另一个项目中调用它,它工作正常:

// 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;
}
Run Code Online (Sandbox Code Playgroud)

但是,当我打电话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;
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助.(PS:我在Windows7上使用VS2010)
更新:
这是依赖步行者为该SimpleDll.dll文件显示的内容:

在此输入图像描述

Joh*_*ohn 5

如果要导出GetProcAddress的名称,则应使用.def文件.否则你将不得不处理c ++名称修改和符号装饰.

您可以通过声明函数来避免修改extern "C",但避免装饰的唯一方法是使用.DEF文件.

还有一件事 - 在Dependency walker中 - 使用F10在装饰和未装饰的名称之间切换.