Tip of the week: using C libs from D

Posted 2021-03-29

Experienced D users surely already know this but newer users should read this tip.

Core D Development Statistics

In the community

Community announcements

See more at the announce forum.

Tip of the Week

Most standard C headers are included in D runtime. If you see #include<unistd.h>, you should try import core.sys.posix.unistd in D and see if it works.

Now the tricky thing is the C tends to just do #include<whatever> and D breaks it up into core.stdc, core.sys.[windows|posix|linux|etc]. The name of the package depends on which standard it comes from.

Easiest way to find this is to check the bottom of the man page for the C function for the "Standards" section too to see which one it is under. If it is a C standard, core.stdc. If it Posix, try core.sys.posix. linux-specific is core.sys.linux, etc.

Then after that it is just the .h file most the time. But note that #include<sys/types.h> keeps the sys thing, so in D, that is probably core.sys.posix.sys.types; - the / becomes a .

There's a few exceptions but this pattern is followed like 98% of the time for standardized systems with the operating system.

There's some functions that aren't referenced there. But there's nothing actually special about the druntime bindings - they are provided simply for convenience. You can also just as well paste extern(C) your_c_function_declaration anywhere in your own code too and call it all the same.

I often just copy/paste the few functions I need into my file instead of making a full binding. Then you can run with it immediately and add more as-needed.