Passing ref T[n] to C

Mike Parker aldacron at gmail.com
Mon Dec 9 07:46:39 PST 2013


Given the following declarations in C:

typedef int foo_t[3];
void take_foo( foo_t );

How would you handle this in D?

It's obvious to me that the type should be declared the same way, so 
that it may be used the same way in D as in C:

alias foo_t = int[3];

Given that on the C side, foo_t[3] parameters will degrade to pointers, 
it's just as obvious to me to declare the function on the D side like so:

extern( C ) void take_foo( foo_t* );

That means that one need pass foo.ptr when calling the function, but it 
doesn't really bother me. However, it was recently brought to my 
attention that the following actually works:

extern( C ) void take_foo( ref foo_t );

foo_t foo = [1, 2, 3];
void take_foo( foo );

I tested it with DMC and DMD and it actually worked fine. I was 
expecting the length field to get in the way, but it didn't seem to. I 
was able to print the values of the array just fine on the C side.

My question is, can I rely on this? Is there a guarantee that a ref 
static array parameter will be compatible with a C array pointer on 
every platform and architecture? A voice in my head is screaming NO at 
me in all caps and with multiple exclamation points. But, if true, it 
would certainly simplify user code by not having to remember to pass 
foo.ptr all the time. So I thought I'd ask. I can't find anything 
regarding the implementation details of ref parameters.





More information about the Digitalmars-d-learn mailing list