Why doesn't this code work (Please See Details)?

2

I have written the following code (x64 VS 2015):

typedef void(__stdcall *foo)(void* v);
HMODULE hmod = GetModuleHandle(NULL);
foo f = (foo) GetProcAddress(hmod, "_foo0");
f(0);

foo0 is defined as:

extern "C" void __stdcall foo0(void* v){int a = 0;}

I have disabled all optimizations and security checks.

What I want the code to do is to find the address of the foo0 and then call it. For some weird reason, calling GetLastError() after GetModuleHandle() returns 0x00000032 which means ERROR_NOT_SUPPORTED, but it does return some nonzero value which I assume is the handle to the executable. GetProcAddress() returns 0x0000000000000000 and a GetLastError() call after it returns 0x0000007f which means ERROR_PROC_NOT_FOUND, but I defined the proc!

Why is this happening? Is GetProcAddress() not supposed to be used with GetModuleHandle()?

c++
winapi
runtime-error
asked on Stack Overflow Dec 14, 2015 by Geekus Maximus • edited Dec 14, 2015 by Geekus Maximus

2 Answers

2

The code fails because GetProcAddress requires the supplied symbol to have been exported from the module in question. That is, the symbol must have been listed in the PE module's export table. You do not export the symbol, and so GetProcAddress cannot find it. Hence GetProcAddress returns NULL. If you wish to use GetProcAddress then you must export the symbol. Either by naming it in a .def file, or by using __declspec(dllexport).

Some other comments:

  1. You appear to have a mismatch of calling conventions, stdcall and cdecl.
  2. You don't perform any error checking. For these particular function you need to check the return value. If that indicates that the function has failed, then call GetLastError for extended error information.
answered on Stack Overflow Dec 14, 2015 by David Heffernan
0

It should be:

extern "C" __declspec(dllexport) void foo0(void* v) { int a = 0; }

and:

foo f = (foo)GetProcAddress(hmod, "foo0");
                                  ^^~~~ no need for underline

as to your GetLastError issue, I am not sure about it - I suppose it might be some random value.

answered on Stack Overflow Dec 14, 2015 by marcinj

User contributions licensed under CC BY-SA 3.0