How to use std. packages in so files written in dlang

ketmar via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Aug 11 19:31:29 PDT 2016


On Friday, 12 August 2016 at 01:36:34 UTC, grampus wrote:
> I can use dlang in this existing project as long as nothing can 
> be changed on the C side.

then you have to check if runtime is initialized at the start of 
each function that can be called from C side. like this:


private void ensureRuntimeInited () {
   static bool tlsinited = false;
   __gshared bool inited = false;
   if (!tlsinited) {
     synchronized(Object.classinfo) {
       if (!inited) {
         import core.runtime : Runtime;
         if (!Runtime.initialize) {
           import core.stdc.stdio : stderr, fprintf;
           import core.stdc.stdlib : abort;
           fprintf(stderr, "\nFATAL: failed to initialize 
druntime!\n");
           abort();
         }
         inited = true;
       }
     }
     tlsinited = true;
   }
}


extern(C) int myExtAPI () {
   ensureRuntimeInited();
   // your D code here
   return 0;
}


yes, you have to do that in each exported function.


as for your another question: if you won't call `rt_term()`, no 
module dtors will be called, no garbage will be collected at 
exit. there also may be problems with unregistering signal 
handlers, but i'm not sure.

if you C app routinely loads and unloads .so without notifying it 
about the fact that .so is being unloaded, you are in big 
troubles not only with D, but with .so written in any other 
language. you *may* hack around this, but it's *WAY* better to 
fix your C app in this case.


More information about the Digitalmars-d-learn mailing list