When loading shared libraries in Windows, LoadLibrary() call causes DllMain in library to execute for each new process and thread library attaches to, and for each process and thread library deattaches from.
Is there similar mechanism for Mac OS X, Linux and possibly other POSIX-compatible OSs?
You can define an on-load function for a linux library using the
.initmechanism. This is the same as specifying the load-time entry point for a binary (e.g. using something other than main as the entry point for a program).When linking using
lddirectly you use the:or if you’re using cc/gcc to link, you use:
This is at it’s most simple level.
Edit
For destructors/finalizers, you use the
.finimechanism. This operates in the same manner as the init option, and you use:when invoking
ld. Availability is limited to the-initoption on the Mac OSX platform.You should also be able to use the
__attribute__((constructor))syntax for gcc:Which is probably a more portable way rather than screwing with the linker options. All constructors should be invoked at load-time, but don’t depend on the order of their initialization, that leads to insanity and unreproducible bugs that cost time and effort to debug.
Edit 2 The use of the
__attribute__((constructor))/__attribute__((destructor))semantic is the most preferable mechanism for the C/C++ programming language.For the
Dprogramming language you should really use the static module constructor/destructor:Or the static class constructor:
This is strongly hinted at in the writing win32 DLLS and in the language specification relating to static constructors/destructors.
Edit 3 You will need to link in a
.othat exports constructor/destructor routines, that will allow the use of the static initializers. As all it should do is call Runtime.initialize(), this actually invokes all the static constructors/destructors in theDcode.Stub d code for the initializer (in a file called
myshared.d):Create the .o for this stub:
Check the names of the attach/detach functions:
Shows (among other output):
sample .c code for invoking this (called export.c in this case), we reference the names of the exported routines from the
my shared.ofile:Note that the
extern voidreferences need to use the mangled name of the exported function. These must match or the code will not link.compile the C code using:
link the .c.o and the .d.o files together using:
Assuming that the phobos2 library is in your standard linker search path. The smatterings of
-m32options for the compiler and linker are because the version of the D compiler that I built locally only supported 32bit.This produces a .dylib that can be linked to. It seems to work based on the limited testing I performed. It looks like support for shared objects/dynamic libraries is very limited, so there is a good chance that there will be another hurdle to overcome.