Passing static arrays to C

Walter Bright newshound2 at digitalmars.com
Wed Oct 24 10:45:07 PDT 2012


On 10/24/2012 2:55 AM, Jakob Bornecrantz wrote:
> On Wednesday, 24 October 2012 at 09:03:25 UTC, Jacob Carlborg wrote:
>> On 2012-10-24 09:54, Jakob Bornecrantz wrote:
>>> Hey everybody.
>>>
>>> How are you supposed to pass static arrays to C functions? I'm asking
>>> because I'm getting conflicting info from how DMD works and on IRC.
>>>
>>> The below example prints:
>>> test1 0x7fff857c1db0
>>> test2 0x7fff857c1db0
>>> test3 (nil)
>>> test4 0x7fff857c1db0
>>>
>>>
>>> D:
>>> void main()
>>> {
>>>         float[3] arr;
>>>         test1(arr);
>>>         test2(&arr[0]);
>>>         test3(0, arr);
>>>         test4(0, &arr[0]);
>>> }
>>>
>>> extern(C):
>>> void test1(float[3] arr);
>>> void test2(float *arr);
>>> void test3(int, float[3] arr);
>>> void test4(int, float *arr);
>>>
>>>
>>> C:
>>> #include <stdio.h>
>>>
>>> void test1(float arr[3]) { printf("test1 %p\n", &arr[0]); }
>>> void test2(float arr[3]) { printf("test2 %p\n", &arr[0]); }
>>> void test3(int anything, float arr[3]) { printf("test3 %p\n", &arr[0]); }
>>> void test4(int anything, float arr[3]) { printf("test4 %p\n", &arr[0]); }
>>
>> That seems weird. Since static arrays are passed by value in D you need to
>> send a reference:
>
> Yeah I'm wondering if this isn't a bug.

In D, static arrays are passed by value, in C by pointer. Hence, you have a 
mismatch between the C and D prototypes of test1, and you'll get garbage results.



More information about the Digitalmars-d mailing list