In Windows there is a DllMain and DLL_PROCESS_ATTACH / DLL_PROCESS_DETACH flags, which allow to initialize / free resources after DLL is attac开发者_运维知识库hed to a process... So how can I specify an entry point in case of OS X? As always, I can't find anything useful in Apple documentation :(
The Dynamic Library Programming Topics document on Apple’s Web site shows the use of
__attribute__((constructor))
and
__attribute__((destructor))
to implement initialisers and finalizers in dynamic libraries.
Wouldn't that work?
__attribute__((constructor)) void DllMain()
{
// code
}
I think malkia (upvoted) and Bavarious have the right answer, but since I already looked it up: One way to do this is to set your init routine. Look for the "Initialization Routine" in your Xcode build settings for your library. Prefix the function name with an underscore. I.e. if your init routine is called DllMain, enter "_DllMain".
Also, I have previously done some initialization using obj-c++ doing something like this:
class LibraryInit
{
public LibraryInit()
{
// do some init stuff here
}
} ;
static LibraryInit sLibraryInit();
My main application statically links to a static library A with a function ABC and my dynamic library xyz.dylib also statically links to the same static library A which has the same function ABC.
Now when the main application Loads xyz.dylib using dlopen on runtime. The initializer gets called where i have called ABC function. This function ABC is getting called from main application's address space. This is really strange and i do not know, what is going wrong? Though it should have called ABC function from the dylib.
精彩评论