Is it possible to create a function in a shared library (.dll on Windows, and .so on linux) that is executed right when the library is loaded (or unloaded)?
Just like the main() function is the entry point for an executable, can I define a function to execute when the DLL is loaded, or unloaded?
E.g.:
void _atstart()
{
// Initialize some stuff needed by the library
}
void _atexit()
{
// Release some allocated resources
}
I think I've seen such an example somewhere, but I couldn't find it any more, and couldn't find anything on the internet about this.
If it is of any use, I'm compiling the code with MinGW.
In C++ you can at least create a global instance of some class
class ResourceHolder {
public:
ResourceHolder() {
// at start
}
~ResourceHolder() {
// at exit
}
};
ResourceHolder theHolder;
Some awareness is required though if you use another global variables in your library.
For windows you can use DllMain:
BOOL WINAPI DllMain(
__in HINSTANCE hinstDLL,
__in DWORD fdwReason,
__in LPVOID lpvReserved
);
The second parameter fdwReason specifies if the library is loaded or unloaded. Full reference: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved)
{
switch (fdwReason)
{
case DLL_PROCESS_ATTACH:
// code for library load
break;
case DLL_PROCESS_DETACH:
// code for library unload
break;
}
return (TRUE);
}
For Linux you might be able to use:
__attribute__ ((constructor))
__attribute__ ((destructor))
but this only came up after a google search, so you have to investigate by yourself - http://tdistler.com/2007/10/05/implementing-dllmain-in-a-linux-shared-library
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With