Why using wrappers for D?

Mike Parker via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Oct 3 06:51:28 PDT 2016


On Monday, 3 October 2016 at 12:08:54 UTC, Chalix wrote:

> Furthermore, if there is an not very popular C library, where 
> no wrapper function exists, would it possible to include it 
> into a D project? Probably I have to transform all the .h to .d 
> files, so i can "import" them instead of "include" them. But 
> then, could I link against the C-library?

Yes, but here you're talking about a binding, not a wrapper.

>
>
> I did not understand the concept of interaction between C and 
> D, and I am a bit confused about wrapper functions and bindings 
> for D now...
> Would be great if someone could make it a bit more clear to me 
> :)

A binding is just the C function declared in D:

// foo.h
extern void my_func(const char *str);

// foo.d
extern(C) void my_func(const(char)* str) @nogc nothrow;

Now with the declaration in D, you can link directly to the C 
library. But you also need foo.d to be linked into your program, 
either by compiling it alongside your own source files or linking 
it as a library (as you do with gtkd-3.lib).

A wrapper takes a C interface and makes it more D like.

// wrapfoo.d
import foo;  // import the foo module from above

void myFunc(string s)
{
     import std.string : toStringz;
     my_func(s.toStringz());
}




More information about the Digitalmars-d-learn mailing list