D calling C?

torhu fake at address.dude
Sat Mar 3 21:20:52 PST 2007


Glenn Lewis wrote:
> Oh, sorry.  Here they are:
> ---------------------------------------
> // t1.d
> import std.stdio;
> 
> extern (C) { float func(float v[]); }
> 
> void main(char[][] argv)
> {
>   float v[2];
>   v[0] = 0.0;
>   v[1] = 1.0;
>   float x = func(v);
>   writefln("x=%g", x);
> }
> ------------------------------------------
> // t2.cpp
> #include <stdio.h>
> 
> extern "C" { float func(float* v); }
> 
> float func(float v[])
> {
>   printf("v[0]=%g, v[1]=%g", v[0], v[1]);
>   return v[0] + v[1];
> }
> --------------------------------------------
> -- Glenn

A dynamic array in D consists of a length and a pointer.  So it's not 
binary compatible with a pointer.  A static array works, though.  If the 
length is fixed at two, you can do this:

extern (C) float func(float v[2]);
float x = func(v);


Or just use a pointer:

extern (C) float func(float* v);
float x = func(v.ptr);


Or have the length as an arg:

extern (C) float func(float* v, size_t n);
float x = func(v.ptr, v.len);


If the C function takes the length first, then the pointer, this also works:

extern (C) float func(float[] v);
float x = func(v);


The last one is a bit ugly, since it depends on the actual layout of 
dynamic array references.  Not that that's likely to change.



More information about the Digitalmars-d mailing list