Why GetProcAddress doesn't work?

霸气de小男生 提交于 2019-12-01 04:00:13

问题


First, I create a simple dll called SimpleDll.dll, its head file:

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

MYLIBAPI int Add(int a. int b);

its source code:

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

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

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

Then I call it in another project, and it works fine:

// 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;
}

However, when I call GetProcAddress to get it's address, it doesn't work!

// 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;
}

Thanks for your help. (PS: I use VS2010 on Windows7)
Update:
This is what the depedency walker show for the SimpleDll.dll file:


回答1:


You should use a .def file if you want to export the name for GetProcAddress. Otherwise you will have to deal with c++ name mangling and with symbol decorations.

You can avoid mangling by declaring your function as extern "C", but the only way to avoid decorations is to use a .DEF file.

One more thing - in Dependency walker - use F10 to toggle between decorated and undecorated names.




回答2:


Dependency Walker is an excellent tool for troubleshooting DLL issues like this.

I'm assuming you are compiling the DLL as C code. Otherwise, C++ performs name mangling that would cause problems.

To avoid name mangling simply wrap the export definition in extern "C".

extern "C" {
    MYLIBAPI int Add(int a. int b);
}


来源:https://stackoverflow.com/questions/5684737/why-getprocaddress-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!