Calling D from C, C++, Python…

Jakob Ovrum via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Sep 13 03:13:46 PDT 2015


On Sunday, 13 September 2015 at 10:10:32 UTC, Jakob Ovrum wrote:
> On Thursday, 10 September 2015 at 18:01:10 UTC, Russel Winder 
> wrote:
>> Is there an easy way of knowing when you do not have to 
>> initialize the D runtime system to call D code from, in this 
>> case, Python via a C adapter?
>>
>> I naïvely transformed some C++ to D, without consideration of 
>> D runtime systems, compiled it and it all worked. Which is 
>> good, but…
>
> Surely the reasonable choice is to always initialize the 
> runtime in a sensible location? What do you gain from not 
> initializing it, and is it really worth the effort?
>
> core.runtime has Runtime.initialize and Runtime.terminate. In a 
> Windows DLL, it's sensible to use DllMain to call these. 
> core.sys.windows.dll.SimpleDllMain is a mixin template that 
> makes it easy:
>
> version(Windows)
> {
>     import core.sys.windows.dll;
>     mixin SimpleDllMain;
> }
>
> On Linux and other ELF-using platforms, initialization and 
> deinitialization functions could be placed in the .init and 
> .deinit special sections, but I don't know if druntime has any 
> convenient provisions for this. With GDC and LDC you can 
> probably use a pragma to put functions in these sections, but I 
> don't know if DMD has such a pragma.
>
> I don't know what the equivalent is for Apple's Mach-O shared 
> libraries.

Note that if the host program can call into the D shared library 
from multiple threads, it's necessary to register those threads 
with the runtime as well. The DllMain solution handles this 
automatically, but for other systems additional handling is 
necessary.


More information about the Digitalmars-d-learn mailing list