问题
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");
回答1:
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:
- There is no exported function named
GetNumber
- There is an exported function named
GetNumber
, but it is not markedextern "c"
, resulting in name mangling. 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();
};
回答2:
Most probably LoadLibrary() failed. You just can't see that because apparently you are not checking what it is returning:
If the function fails, the return value is NULL. To get extended error information, call GetLastError.
EDIT:
We don't know how you are exporting the function on the DLL code, but this thread explains a couple of reasons on why GetProcAddress fails.
回答3:
You might want to check if your GetNumber
function is exported as an __stdcall
function.
If so, try GetProcAddress(hDLL, "_GetNumber@N");
, where N
is the total number of bytes of GetNumber
's argument list. For example, if your function signature is int GetNumber(int a, double b)
, its real name in DLL will be _GetNumber@12
.
Reference: __stdcall
来源:https://stackoverflow.com/questions/6031431/getprocaddress-function-in-c