Some Online Writings

This is almost a blog

View the Project on GitHub bachmeil/online-writing

The many paths to easy interoperability of C and D code

tags:

Motivated by a recent Hacker News discussion.

  1. ImportC lets you compile C code. It has extern(C) linkage and the D compiler understands it. In other words, you don’t have to do anything to call C functions you’ve compiled with the D compiler.
  2. BetterC lets you continue to write C code while taking advantage of improvements as you wish. There’s no runtime at all. That means there’s no garbage collector. Normally you’d use this as a way to embed D functions inside a C program without adding anything other than your D functions.
  3. Create a shared library in D and call it trivially from C or any other language with a FFI. Since your functions have extern(C) linkage, the other language thinks it’s working with C. This is how I call D functions from R.
  4. Call C shared libraries from D. You can write bindings yourself without a lot of effort, since D is a superset of C. That’s no longer how most of us do it. Dstep will write the bindings for you. dpp lets you #include C header files directly in your D program. The aforementioned ImportC that is part of the compiler can compile header files for you.
  5. Compile C files with a C compiler like gcc and then add the produced .o files to your D compilation. You’ll need to use one of the approaches in the previous point to create the bindings.
  6. Compile your D files and include the .o files in a C project. I’ve never done this, and you’d probably have to link to the runtime and maybe other things, but it should work with minimal effort.

There are many options. All of them require only minimal effort. An experienced C programmer does not need to give up what they know to benefit from D. You can use D incrementally. You can use it as little or as much as you want. You can write in a C style and but only take advantage of D array slicing and bounds checking. Or maybe you want to continue writing the same C code but with D’s metaprogramming. Maybe you’re like me. You’d rather not write C code at all. You only deal with it because there’s a lot of useful existing C libraries. You mostly write D, using many of its features, but you also link to C libraries.


13 January 2021

Post written by Lance Bachmeier