tags:

views:

60

answers:

3

I have work I need to complete in a DLL as soon as it is loaded. The work involves synchronization and so can't be done inside dllmain. Is there a way to trigger code to execute as soon as dllmain (or all dllmains) is complete?

A: 

The easiest way is to probably put all the code into another function which you call after the library is loaded.

You could also create a thread that does the work but I'm not sure exactly what you're trying to do.

Brian R. Bondy
+2  A: 

This has long been a thorny issue from my point of view. If the DLL is being used by 3rd party applications over which you have no control, then it is difficult be able to force the other applications to call some initialization function. Ultimately, it can be a requirement, but it is certainly nice to not have to do that to use a DLL (e.g., initializing winsock).

If an initialization call is not possible, it is likely that you need to rely on lazy initialization that happens on demand. I ran across a pretty decent paper on DLL Best Practices that may be worth reading. It has a good list of specific things that you can and cannot do inside DLLMain. I know from experience that these need to be adhered to (the "do not" list).

Mark Wilkins
+3  A: 

According to this MSDN post:

During process startup and DLL initialization routines, new threads can be created, but they do not begin execution until DLL initialization is done for the process.

If this holds true, then you should be able to do your work in the Thread in question, which will not start until the DLLMain has completed. Of course this leaves some possible synchronization issues open, If you use a Mutex maybe you can resolve this.

NOTE: I have not tried this, it just looks like in theory it might work.

P.S. If you try it pls leave a comment on whether it worked or not.

Romain Hippeau
Just as a note: the 'best practices' document referred to in Mark Wilkins' answer recommends against calling `CreateThread()` (though it does acknowledge that it can be done). Tread carefully if you decide to go down that route.
Michael Burr
I agree the best way to do this is to create an initialization routine and have users of the DLL call that as part of the API. It is common i.e. WinSock and IBM MQSeries
Romain Hippeau
Spinning off a thread seems to have worked. According to Raymond Chen, you have to be careful what you do there because you can deadlock if you wait on that thread from inside dllmain. See http://blogs.msdn.com/oldnewthing/archive/2007/09/04/4731478.aspx
Steve Rowe
@Steve Rowe - Glad to hear ... thx
Romain Hippeau