Passing D arrays to a C interface

torhu no at spam.invalid
Mon Nov 5 01:13:22 PST 2007


Simen Haugen wrote:
> I'm building a library that should be callable from C, but I'm having 
> problems with arrays.
> The D documentation says there are no equivalent for dynamic arrays in C, so 
> how can I pass D arrays to C? Is this also a problem with other languages 
> like Pascal? 
> 

When you say 'pass D arrays to C', I assume you mean D code calling C 
functions?

That would look like this:

---
extern (C) void C_func_called_by_D(int* data, size_t length);

void tryit() {
     int[] a = [1, 2, 3];

     void C_func_called_by_D(a.ptr, a.length);
}
---

D dynamic arrays are not (portably) link-compatible with anything in C. 
  Most of the time you would get away with pretending they are a 'struct 
dynarray { size_t len; void* data; };'  But it's probably better to pass 
the size and the pointer separately, like in the example.

If C code passes an array as a pointer and a length to D, you can turn 
it into a dynamic array with something like this:

T[] toArray(T, U)(T* ptr, U len)
{
     return ptr[0..len];
}


Static (fixed-size) D arrays are compatible with C arrays when used as 
function arguments.  They are passed as the address of the first 
element, just like in C.

Be aware that this C prototype:

void f(int a[]);

is not compatible with this D prototype:

extern (C) void f(int[] a);

but with this one:

extern (C) void f(int* a);

But you have the length of the array in C:

void f(float vec[3]);

It's compatible with the same declaration in D.  At least until they 
become pass-by-value in D2.0...


I can't remember how arrays work in Pascal, sorry. :)



More information about the Digitalmars-d mailing list