I’m trying to build a DLL which I would later like to inject into some processes using the SetWindowsHookEx() function. Strange thing is that when I try to load the DLL and try to get use GetProcAddress to get the address of the procedure contained within it, it returns NULL if I try to get the address of the CBT message handling procedure, but it works fine for the other functions.
This is the code.
DLL HEADER (.h)
#include <windows.h>
extern "C" {
__declspec(dllexport) LRESULT CALLBACK hookProc(int code, WPARAM wParam, LPARAM lParam);
__declspec(dllexport) int add(int a, int b);
}
DLL FILE (.cpp)
#include "SimpleHook.h"
extern "C" {
__declspec(dllexport) LRESULT CALLBACK hookProc(int code, WPARAM wParam, LPARAM lParam) {
return CallNextHookEx(0, code, wParam, lParam);
}
__declspec(dllexport) int add(int a, int b) {
return a + b;
}
}
MAIN FILE
#include <iostream>
#include <windows.h>
#include <tchar.h>
int main(int argc, char* argv[]) {
HINSTANCE dllHandle = LoadLibrary(_T("SimpleHook.dll"));
if (dllHandle) {
// returns the correct address
cout << "add address: " << GetProcAddress(dllHandle, "add") << endl;
// returns NULL
cout << "hookProc address: " << GetProcAddress(dllHandle, "hookProc") << endl;
}
}
If I use GetLastError() I get the 127 error code with means:
ERROR_PROC_NOT_FOUND: The specified procedure could not be found.
Strange thing is that the other functions from the same file are loaded correctly.
Any help is greatly appreciated!
The calling convention changes the name mangling.
__stdcallfunctions always have their names prepended by_and mangled in some other ways too, so the link fails, but the__cdeclfunction isn’t mangled and so it’s found.To import from a DLL that you built with
__declspec(dllexport), you should always include a header with__declspec(dllimport)on everything you want to import and link the lib you got from building the DLL. This will guarantee that all of your functions link correctly, and you don’t have to go down to C-compatible linking.You shouldn’t be using
GetProcAddress, norextern "C"in conjunction with__declspec(dllexport).Header:
DLL .cpp file:
Main .cpp file:
Don’t forget to add the lib to the linker.