Open faustinoaq opened 7 years ago
I don't think static arrays can be passed around in C, so maybe this shouldn't even compile. Maybe it's a bug, but it has very low priority.
@asterite Yes C don't allow array literal as argument but array pointer
Pass by reference work as in C
fun print_chrray(sarr : Char[5]*)
puts sarr.value
end
sarr = StaticArray(Char, 5).new('x')
print_chrray(pointerof(sarr)) # => StaticArray['x', 'x', 'x', 'x', 'x']
What do you mean by passing array literal in C, I got this to work: (C code)
#include <stdio.h>
int func(const int bla[3])
{
return bla[0];
}
int main()
{
printf("%d\n", func( (const int[3]){42, 43, 44} )); // => 42
return (0);
}
Is it what you're trying to do in Crystal @faustinoaq ?
@bew You're right. I was confused. My mistake :sweat_smile:
@bew Actually, you're just passing a pointer to the first element of the array, because C is C and reasons unknown.
@kirbyfan64 You're right, and I was confused too, so @faustinoaq you're right 😄
edit:
I think the type syntax in fun
is weird, because in C:
void print_chrray(char value[5]);
The argument value
has type char*
, and in Crystal, you need an extra *
to represent the same thing:
fun print_chrray(value : Char[5] *)
It feels weird, because then the crystal type Char[5]
has no representation in C (if I understand it well)
@bew Well...
Actually, C already completely ignores the bound on an array parameter. So, like you already said, value
is of type char*
in C. Therefore, the equivalent in Crystal is just Char*
(no [5]
).
Maybe C ignore bounds, but Crystal doesn't, so i like this little bit of additional typesafety in bindings: https://github.com/konovod/monocypher/blob/master/src/monocypher/libmonocypher.cr. Never encountered this issue though, maybe because i wrap all staticarrays in a structs with to_unsafe method.
I was playing with
fun
and found something. I try to show you a minimal example:The above code produce the following message: