Need extern (C) interface even though using Derelict GLFW
Mike Parker via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Jan 4 20:42:46 PST 2015
>
> Are they some extremely simple tutorials on bindings and
> wrappers? Something with lots of code examples.
I don't think it's a subject that warrants a tutorial. There's
not that much to it. Consider:
####
// capi.h
void do_something( const char *str );
// capi.d -- this is a binding
extern( C ) void do_something( const( char )* str );
// capiwrapper.d -- this is a wrapper
void doSomething( string str )
{
import std.string : toStringz;
do_something( str.toStringz() );
}
####
That's all there is to it. The binding allows you to call C
functions from D. The wrapper adds a more convenient D interface
on top of the C function.
Of course, there are numerous details to consider when
implementing a binding (some of which you can see at [1]), but
you generally don't need to worry about them as a user. There are
exceptions, though, when you need to be aware of what's going on.
One of those is when implementing callbacks. All you really need
to understand is that the calling convention of the C functions
may not be the same as that of D functions. That's why the C
function above is decorated with extern( C ) -- it uses the cdecl
calling convention (see [2] for an explanation of different x86
calling conventions). So any callbacks you pass into the API need
to be of the same calling convention, because they are actually
being called on the C side, not the D side.
[1] http://dlang.org/interfaceToC.html
[2] http://en.wikipedia.org/wiki/X86_calling_conventions
More information about the Digitalmars-d-learn
mailing list