On Tuesday, September 25, 2018 5:03:11 AM MDT John Burton via Digitalmars-d- learn wrote: > I need to write a library to statically link into a c program. > Can I write this library in D? > Will I be able to use proper D abilities like gc? Obviously the > public interface will need to be basic c callable functions... > > I 'main' is a c program will this work?
If you use -betterC, then it's trivial, because your D program is restricted to extern(C) functions and features which don't require druntime. It can also be done without -betterC (and thus with druntime), but it gets to be _way_ more of a pain, because it requires that you manually initialize druntime - either by forcing whatever is using your "C" library to call a specific function to initialize druntime before using any of its normal functions or by having every function in the library check whether druntime has been initialized yet and initialize it if it hasn't been before it does whatever it's supposed to do. And of course, if you pass any GC-allocated memory out of the library, you have to worry about calling all of the appropriate GC functions so that it knows not to free it and knowing when to tell the GC that that memory can be freed. It's all very feasible and all very annoying. In general, it's far, far easier to write D programs that call into C code than to write C programs that call into D code. That's part of why some folks are so excited about -betterC. It makes it _way_ easier to write D libraries that can be called from C or C++ - though because you lose out on so many D features in the process (like the GC), whether it's even worth it is highly debatable. - Jonathan M Davis