I've been trying to write DLLs for the first time, and have a project I'm attempting to work on. I write my DLL, which is the simplest DLL I'm able to think of, and then compile it. I go to my executable, call LoadLibrary, which loads it just fine, and I'm able to call functions from the DLL like normal. FreeLibrary, however, returns 1 every single time. I have yet to be able to successfully unload a DLL (I'm playing around with hot-reloading DLLs and this is my hacked together solution just for practice).
Here's my code:
Executable's program.cpp:
#include <iostream>
#include <windows.h>
typedef void (*_TestFunction)();
int main()
{
HMODULE hinstDLL = LoadLibrary(L"Test.dll");
_TestFunction TestFunction = (_TestFunction)GetProcAddress(hinstDLL, "TestFunction");
TestFunction();
BOOL result = FreeLibrary(hinstDLL);
std::cout << result << std::endl;
if (hinstDLL != NULL)
{
std::cout << "Still loaded" << std::endl;
}
std::cin.ignore();
return 0;
}
My DLL's dllmain.cpp:
#include "pch.h"
#define DLL_EXPORT
#include "dllmain.h"
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
std::cout << "DLL Load Process" << std::endl;
break;
case DLL_THREAD_ATTACH:
std::cout << "DLL Load Threaded Process" << std::endl;
break;
case DLL_THREAD_DETACH:
std::cout << "DLL Unload Threaded Process" << std::endl;
break;
case DLL_PROCESS_DETACH:
std::cout << "DLL Unload Process" << std::endl;
break;
}
return TRUE;
}
DLL_FUNCTION void TestFunction()
{
std::cout << "Hello World" << std::endl;
}
dllmain.h:
#pragma once
#ifdef DLL_EXPORT
#define DLL_FUNCTION extern "C" __declspec(dllexport)
#else
#define DLL_FUNCTION extern "C" __declspec(dllimport)
#endif
My precompiled header only contains iostream for the DLL to log information, and for the TestFunction()
.
I have no clue why it isn't working, and I've been stuck on this problem for almost a full day now. Any help is appreciated.