Global pointer in DLL

479 views Asked by At

I have a C++ DLL project which contains a dllmain source file, a header with just the DLL function declarations, and a cpp file which contains the full function definitions, and a global pointer to an instance of a different class. This pointer is initialised with a call to an Init function, and all the rest of the DLL functions use the pointer and return an error if it has not been allocated.

Other than relying on the user to call a specific function when they're finished with the DLL (which sounds like a terrible idea) how can I make sure that the global pointer in the cpp file is deallocated?

Thanks.

2

There are 2 answers

0
Mark Ransom On BEST ANSWER

When the DLL is being shut down there will be a call to DllMain with a parameter of DLL_PROCESS_DETACH; you can put code to free your global there.

0
James M On

Other than relying on the user to call a specific function when they're finished with the DLL (which sounds like a terrible idea)

Considering you already have an Init function, having a matching Free function makes sense.

How else would you know when the user is done with the library? You could wait until the DLL is unloaded (see DllMain) but by that time the process is probably ending anyway.

I suppose the best solution would be to avoid the global pointer entirely. Make a class that contains the instance of the other class and your methods, and have the user create an instance themselves (the constructor replacing your Init and the destructor replacing your Free).