#Passing a fixed size array to a C function
18 messages · Page 1 of 1 (latest)
I guess this is something we assume from the caller and we cannot assert this is the case?
Though I wonder if there is a better type, because array should not need a ptr maybe?
I guess I dont know what to put as the rust argument
#[no_mangle]
pub extern "C" fn my_func(array : [u8;64]) { }
Into maybe
#[no_mangle]
pub extern "C" fn my_func(array : *const u8) { }
Oh seems we always need to allocate I think, not sure
The C pattern, would effectively be to pass a pointer, with a length, which is effectively combined in Rust, as a slice... a fat reference to a length of a contiguous section of memory... though, if you wanted to pass a statically sized array by value, the first example would be appropriate... otherwise, it could be specified by pointer, or preferably, by reference...
what would the c type look like?
I'm using c_bindgen and it seems I can only supply *const u8
Oh I guess thats a limitation with c bindgen
Why would I pass the length, when the array length is known?
Well, if you're passing by reference, it wouldn't be.
If you're passing by value, that should be statically enforceable...
Because it's not known in C
These definitions are entirely equivalent in C:
void my_func(uint8_t array[64]);
void my_func(uint8_t array[]);
void my_func(uint8_t *array);
The number between the [] is entirely decorative, and you can omit it, yes
Arrays decay to pointers anyway
To actually pass an array by value, you need to do this hack
typedef struct {
uint8_t array[64];
} uint8_64_t;
void my_func(uint8_64_t array)