GetProcAddress function in C++

痴心易碎 提交于 2019-11-27 19:51:15

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();
};

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!