Calling C function with static array includes length and pointer

mwarning moritzwarning at web.de
Mon Jun 21 14:59:16 PDT 2010


On Mon, 21 Jun 2010 14:38:50 -0700, Ali Çehreli wrote:

> mwarning wrote:
>> Hi,
>> 
>> I try to pass a static array to a variadic C function. Looks like the
>> array is passed by values as expected, but the length and pointer are
>> prepended, too. Is this intentional or a bug?
>> 
>> http://pastebin.com/6ejFF37j
> 
> Fixed sized arrays don't have ptr and length members:
> 
> import std.stdio;
> 
> void main()
> {
>      int[5] array;
>      writeln(array.sizeof);           // prints 20 writeln(array.ptr, '
>      ', &array); // prints the save value
> }
Hm? You just have proved that they have. :>
But those are not members of a struct/pair instance (as for dynamic 
arrays). They are compile time values.
Whatever, it's me nitpicking. :)

> The code you've pasted has this:
> 
> extern(C) void* foo(uint x, ...)
> {
>      Stdout("x: ")(x).nl;
>      Stdout("y: ")(*(&x + 1)).nl; //outputs 64! return null;
> }
> 
> The expression *(&x + 1) is undefined behavior, because (&x + 1) is not
> valid, i.e. not specified to be accessible by the language.
> 
> Ali
True, the D spec doesn't specify the memory layout.
But the C calling convention does (depending on the platform).

Anyway, the D spec says:
"Static arrays are value types, but as in C static arrays are passed to 
functions by reference and cannot be returned from functions."
(http://www.digitalmars.com/d/1.0/arrays.html#static-arrays)

It seems that D does a little more then just pass by value. It includes 
the pointer and length value as well.

Btw.: smth. told me workaround/solution: wrap the static array in a 
struct.



More information about the Digitalmars-d mailing list