Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code executed by shared library when loaded/unloaded

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.

like image 242
Tibi Avatar asked Sep 06 '26 09:09

Tibi


2 Answers

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.

like image 85
unkulunkulu Avatar answered Sep 07 '26 23:09

unkulunkulu


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

like image 37
Luchian Grigore Avatar answered Sep 07 '26 21:09

Luchian Grigore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!