Can I create static c callable library?

Mike Parker aldacron at gmail.com
Wed Sep 26 10:45:01 UTC 2018


On Wednesday, 26 September 2018 at 09:54:22 UTC, John Burton 
wrote:
>
> Is there any documentation anywhere that deals with calling D 
> from C? I could find plenty the other way round. I think I'll 
> give up on the idea though, and rewrite the whole thing in D :)

Rewriting it in D is a great idea ;) But for the record, much of 
what you've read about calling C from D applies the other way, 
too. You just need to write your D functions as extern(C), 
following the same approach to function signatures and types as 
you've read about, then declare the crossover functions and types 
in C.

One gotcha to look out for is when you call a D function that 
allocates GC memory. In that case, you need to keep a reference 
to it alive on the D side. If it's only being allocated for use 
in C, you can call GC.addRoot [1] when you allocate the memory on 
the D side and GC.removeRoot [2] when you no longer need it.

Also keep in mind that D variables thread-local, and if you need 
to access any of them in C from multiple threads they would 
better be declared as __gshared in D.

[1] https://dlang.org/phobos/core_memory.html#.GC.addRoot
[2] https://dlang.org/phobos/core_memory.html#.GC.removeRoot


More information about the Digitalmars-d-learn mailing list