Reputation: 1146
I created a DLL file (helloWorld.dll):
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#define DLL_FUNC extern "C" __declspec(dllexport)
DLL_FUNC int __stdcall Hello() {
MessageBox(HWND_DESKTOP, "Hello, world", "MEssage", MB_OK);
return 0;
}
After that I created a cpp where I would like to call (useDLL.cpp)
#include <windows.h>
#include <stdio.h>
int main () {
typedef void (*pfunc)();
HINSTANCE hdll = LoadLibrary("HelloWorld.dll");
pfunc Hello;
Hello = (pfunc)GetProcAddress(hdll, "hello");
Hello();
return 0;
}
How can I call the Hello() function?
Upvotes: 1
Views: 364
Reputation: 613451
The code in the question contains a number of errors:
LoadLibrary
returns HMODULE
and not HINSTANCE
GetProcAddress
, returns NULL
and then bombs when you try to call the function at NULL
.So you need something like this:
typedef int (__stdcall *HelloProc)();
....
HMODULE hdll = LoadLibrary("HelloWorld.dll");
if (hdll == NULL)
// handle error
HelloProc Hello = (HelloProc)GetProcAddress(hdll, "_Hello@0");
if (Hello == NULL)
// handle error
int retval = Hello();
The function name is decorated because you used __stdcall
. If you had used __cdecl
, or a .def file, then there would have been no decoration. I'm assuming MSVC decoration. It seems that decoration differs with your compiler, mingw, and the function is named "Hello@0"
.
Frankly it's much easier to do it with a .lib file instead of calling LoadLibrary
and GetProcAddress
. If you can, I'd switch to that way now.
Upvotes: 5
Reputation: 1804
You need to specifically search and find specific functions you are lookins for, check out this link: Calling functions in a DLL from C++
Upvotes: 0