Interfacing D functions from Racket

:: D, racket

This is how you can use a function written in D from a Racket script.

In a file called logc.d:

import std.stdio;

extern(C)
void hello()
{
  writeln("hi from D");
}

Compile to a shared library with:

$ ldc2 -shared -m64 logc.d

or with

$ dmd -shared -m64 -fPIC -defaultlib=libphobos2.so logc.d

Use the generated liblogc.so (or liblogc.dylib) from a Racket script:

(require ffi/unsafe)

(define logc-lib (ffi-lib "liblogc"))

(define logc-hello
  (get-ffi-obj "hello" logc-lib
               (_fun -> _void)))

Try the results:

> (logc-hello)
hi from D

This post is based on Call D from Ruby using FFI and tutorial using racket’s ffi