Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetProcAddress function in C++

Tags:

Hello guys: I've loaded my DLL in my project but whenever I use the GetProcAddress function. it returns NULL! what should I do? I use this function ( double GetNumber(double x) ) in "MYDLL.dll"

Here is a code which I used:

typedef double (*LPGETNUMBER)(double Nbr); HINSTANCE hDLL = NULL; LPGETNUMBER lpGetNumber; hDLL = LoadLibrary(L"MYDLL.DLL"); lpGetNumber = (LPGETNUMBER)GetProcAddress((HMODULE)hDLL, "GetNumber"); 
like image 945
Alireza Avatar asked May 17 '11 13:05

Alireza


People also ask

What does GetProcAddress() do?

GetProcAddress verifies that the specified ordinal is in the range 1 through the highest ordinal value exported in the . def file. The function then uses the ordinal as an index to read the function's address from a function table.

What is Loadlibraryexw?

LoadLibraryEx can load a DLL module without calling the DllMain function of the DLL. LoadLibraryEx can load a module in a way that is optimized for the case where the module will never be executed, loading the module as if it were a data file.

What is Getmodulehandlew?

The GetModuleHandle function returns a handle to a mapped module without incrementing its reference count. However, if this handle is passed to the FreeLibrary function, the reference count of the mapped module will be decremented.

What is CreateRemoteThread?

The CreateRemoteThread function causes a new thread of execution to begin in the address space of the specified process. The thread has access to all objects that the process opens. Prior to Windows 8, Terminal Services isolates each terminal session by design.


1 Answers

Checking return codes and calling GetLastError() will set you free. You should be checking return codes twice here. You are actually checking return codes zero times.

hDLL = LoadLibrary(L"MYDLL.DLL"); 

Check hDLL. Is it NULL? If so, call GetLastError() to find out why. It may be as simple as "File Not Found".

lpGetNumber = (LPGETNUMBER)GetProcAddress((HMODULE)hDLL, "GetNumber"); 

If lpGetNumber is NULL, call GetLastError(). It will tell you why the proc address could not be found. There are a few likely scenarios:

  1. There is no exported function named GetNumber
  2. There is an exported function named GetNumber, but it is not marked extern "c", resulting in name mangling.
  3. hDLL isn't a valid library handle.

If it turns out to be #1 above, you need to export the functions by decorating the declaration with __declspec(dllexport) like this:

MyFile.h

__declspec(dllexport) int GetNumber(); 

If it turns out to be #2 above, you need to do this:

extern "C" {   __declspec(dllexport) int GetNumber(); }; 
like image 92
John Dibling Avatar answered Sep 17 '22 05:09

John Dibling