D Bits

  • entries
  • comments
  • views

Binding D to C Part Two

Sign in to follow this  
Followers 0


This is part two of a series on creating bindings to C libraries for the D programming language.

In part one, I discussed the difference between dynamic and static bindings and some of the considerations to take into account when deciding which way to go. Here in part two, I'm going to talk about an important aspect of function declarations: linkage attributes.

When binding to C, it is critical to know which calling convention is used by the C library you are binding. In my experience, the large majority of C libraries use the cdecl calling convention across each platform. Modern Windows system libraries use the stdcall calling convention (older libraries used the pascal convention). See this page on x86 calling conventions if you want to know the differences.

D provides a storage class, extern, that does two things when used with a function. It tells the compiler that the given function is not stored in the current module and it specifies a calling convention via a linkage attribute. The D documentation lists all of the supported linkage attributes, but for C bindings the three you will be working with most are C, Windows and System.

Although I'm not going to specifically talk about static bindings in this post, the following examples use function declarations as you would in a static binding. For dynamic bindings, you'll use function pointers instead.

The C attribute is used on functions that have the cdecl calling convention. If no calling convention is specified in the C headers, it's safe to assume that the default convention is cdecl. There's a minor caveat in that some compilers allow the default calling convention to be changed via the command line. This isn't an issue in practice, but it's a possibility you should be aware of if you don't have control over how the C library is compiled.

// In C
extern void someCFunction(void);

// In D
extern(C) void someCFunction();

The Windows attribute is used on functions that have the stdcall calling convention. In the C headers, this means the function is prefixed with something like __stdcall, or a variation thereof depending on the compiler. Often, this is hidden behind a define. For example, the Windows headers use WINAPI, APIENTRY, and PASCAL. Some third party libraries will use these same defines or create their own.

// In C
#define WINAPI __stdcall
extern WINAPI someWin32Function(void);

// In D
extern(Windows) someWin32Function();

The System attribute (extern(System)) is useful when binding to libraries, like OpenGL, that use the stdcall convention on Windows, but cdecl on other systems. On Windows, the compiler sees it as extern(Windows), but on other systems as extern( C ). The difference is always hidden behind a define on the C side.

// In C
#ifdef _WIN32
#define MYAPI

extern MYAPI void someFunc(void);

// In D
extern(System) void someFunc();

The examples above are just examples. In practice, there are a variety of techniques used to decorate function declarations with a calling convention. It's important to examine the headers thoroughly and make no assumptions about what a particular define actually translates to.

One more useful detail to note is that when implementing function declarations on the D side, you do not need to prefix each one with an extern attribute. You can use an attribute block like so:

void functionOne();
double functionTwo();

// Or, if you prefer
void functionOne();
void functionTwo();

In part three, I'll talk a bit about builtin types and how they translate between C and D. After that, we'll be ready to look at complete function declarations and how they differ between static and dynamic bindings.

Sign in to follow this  
Followers 0


I just can't wait for parts 3 and 4.

How lucky I am ! You don't treat static linking like if nobody was using it, as so many writers do in their articles. There is an actual need for that kind of linking. My current project heavily relies upon that several important functional features.

I am also very interested in dynamic linking, especially about resource management, garbage collection, ... because when I try to make my code safe, it looks awful as if D was getting in my path. I hope I am just not using all of its power.

Share this comment

Link to comment
I'm not going to be talking about resource management or garbage collection at all, as they play no part in binding to C. And just to be clear, having a static binding does not necessarily imply static [i]linking[/i]. While it can be used to link to a static library, it can also be used to link dynamically with a DLL via an import library on Windows or a shared object file on Posix systems. And by dynamic binding I'm talkiing about manually loading a shared library (DLL or SO) via OS commands at runtime (i.e. LoadLibrary on Windows and dlopen elsewhere).

Share this comment

Link to comment

although you mentioned that you don't have experience with SWIG and htod
tools, I'd like to note that there are two other tools I'm aware of:[list]
[*]CWrap (https://bitbucket.org/denis_sh/cwrap/overview) and
[*]dstep (https://github.com/jacob-carlborg/dstep)

which might be worth of exploring.

Coming from Haskell where there is nice binding tool named c2hs, I'd like to
know/learn not just how to provide D wrapper for C library, but to be able to
provide higher-level D-ish API.

For instance, there is one C library which I'd like to use and the typical
function in its C API looks like:

[CODE]int swe_calc(double tjd_et, int ipl, int iflag, double *xx, char *serr)[/CODE]

where integer return value is not the real result of the computation, but just
handles error conditions (typical C style) in a sense that int < 0 denotes
some fatal error for which the appropriate message is put into char* serr.

Otoh, real return values are stored in array of 6 doubles (double* xx.

So, I'd like to use exceptions in D to handle errors and store real return
value from the function in some data container (e.g. array of 6 doubles) and
in that way have nicer and higher-level D API which is more pleasant to use
for end users.

Do you have any plan to tackle such thing or you're more focused to lower-
level details?


Share this comment

Link to comment
Honestly, I haven't given that sort of thing any thought. I've been using C so long that it doesn't bother me to check return values or store results in a pointer arg, so I've never even considered what a higher level wrapper would look like. Even with my little Dolce project, the idea was just to package up a lot of boilerplate and provide some utilities while explicitly avoiding any sort of wrapping of specific functions. But it's certainly something to consider.

Share this comment

Link to comment
[quote name='Aldacron' timestamp='1328181693']
Honestly, I haven't given that sort of thing any thought...But it's certainly something to consider.

May I point you at this [url="http://book.realworldhaskell.org/read/interfacing-with-c-the-ffi.html"]chapter[/url] in the Real World Haskell book which nicely illustrates this concept.


Share this comment

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now