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()
?
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:
stdcall
and cdecl
.GetLastError
for extended error information.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.
User contributions licensed under CC BY-SA 3.0