Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why GetProcAddress doesn't work?

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:

enter image description here

like image 926
wong2 Avatar asked Apr 16 '11 05:04

wong2


2 Answers

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.

like image 174
John Avatar answered Nov 15 '22 14:11

John


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);
}
like image 41
Judge Maygarden Avatar answered Nov 15 '22 16:11

Judge Maygarden