• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.

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