How to compile Phobos with other D code to create a shared library?

Adam D. Ruppe destructionator at gmail.com
Mon May 31 22:00:35 UTC 2021


On Monday, 31 May 2021 at 21:46:09 UTC, data pulverizer wrote:
> Something interesting is using arrays. I can see that if you 
> instantiate an array within the D function using `new`, for 
> instance

Passing one of those to a C function is iffy anyway because the C 
function can hide it from the garbage collector.

What happens here is Runtime.terminate does a final GC sweep to 
gracefully clean up as much as it can before it close... and it 
thinks that array is unused, so it frees it.

GC.addRoot(array) can tell it not to free normally... but i'm not 
sure if runtime.terminate cares about that since terminate makes 
it think the whole thing is going down anyway.

> auto result = cast(double*)malloc(double.sizeof * n);
> ```
>
> you're left with the issue of not being able to free the memory 
> since you've terminated the runtime.

You can free still, malloc and free are not controlled by the D 
runtime.

This is sometimes a better idea anyway when passing it to C 
function. I don't know how Julia does it though.

> So I guess you have to appropriately pair up `initialize` and 
> `terminate` as appropriate to kind of *startup* and and 
> *shutdown* the connection with druntime with your allocations 
> if they stay within D?

But yeah the best way to do it is to initialize once on library 
load then terminate once when the whole thing is finished.

Typically C plugin systems have some hook for this you can use. 
Like some onload function they define you can use or something.


More information about the Digitalmars-d-learn mailing list