I have DLL which reads and writes some text files. My main program writes a text file named Parameters.txt
as an input data for DLL. I use LoadLibrarу()
function to link DLL with my main program at the run time. After a function call from DLL, which reads Parameters.txt
file and produce some output, I use FreeLibrary()
function to unload DLL.
The problem is that after unloading DLL it still blocks Parameters.txt
for further editing or removing.
#include <windows.h>
int main() {
// create Parameters.txt input data file
create_parameters_file(file_path, /*... some stuff to write in file ... */);
// function pointer alias
using FuncPtr = void (*)();
HINSTANCE hDLL;
// DLL function pointer
FuncPtr composition_func_ptr;
// load DLL
hDLL = LoadLibrary(dll_path);
if (!hDLL) return -1;
// getting function by name
composition_func_ptr = (FuncPtr)GetProcAddress((HMODULE)hDLL, "Composition");
if (!elements_in_system_func_ptr || !composition_func_ptr) return -1;
// calling DLL function. It reads Parameters.txt and create some output text file
composition_func_ptr();
// unload DLL
FreeLibrary(hDLL);
// create Parameters.txt input data file AGAIN
create_parameters_file(file_path, /*... some OTHER stuff to write in file ... */);
return 0;
}
And this is how create_parameters_file()
looks like:
void create_parameters_file(const std::string& file_path, /* stuff to write */)
{
bool file_opened = true;
std::ofstream out_file(file_path);
file_opened = out_file.is_open(); // this returns FALSE after DLL function call
out_file << ...
out_file.close();
}
Is there any way to unload DLL completely so it cannot block the file?
I circumvented the problem by calling an auxiliary application via CreateProcess()
and loading DLL there. Looks cumbersome, but makes work buggy DLL.