Linux shared library loading/linking from C does not invoke (shared) static this
ichneumwn
idonotenjoyemail at idonotenjoyemail.org
Tue Jan 12 10:16:50 UTC 2021
On Tuesday, 12 January 2021 at 09:49:46 UTC, Mike Parker wrote:
> On Tuesday, 12 January 2021 at 09:31:08 UTC, ichneumwn wrote:
>
>>
>> Follow on to my own question: on Linux, with gcc, I have
>> created the following file "starter.c" that I inject into my D
>> shared library:
>>
>> int rt_init(void);
>> int rt_term(void);
>>
>> // should really check for errors!
>> static void __attribute__((constructor)) Dstarter(void) {
>> rt_init();
>> }
>>
>> static void __attribute__((destructor)) Dterminator(void) {
>> rt_term();
>> }
>>
>> That seems to do the trick. Not sure how clean this is?
>
> You should be able to do the same in D with
> `pragma(crt_constructor)` and `pragma(crt_destructor)`:
>
> https://dlang.org/spec/pragma.html#crtctor
> https://dlang.org/spec/pragma.html#crtdtor
> https://dlang.org/changelog/2.078.0.html#crt-constructor
Perfect, thanks! Interestingly, as I removed the C stub and tried
the D route, I noticed that just calling rt_init() is enough to
also get static ~this() to run on exit. In fact then adding
writeln in a pragma(crt_destructor) function shows that it gets
called after static ~this().
For anyone stumbling across this thread and looking for the
import for rt_init/term:
import core.runtime : rt_init, rt_term;
More information about the Digitalmars-d-learn
mailing list