C-type `char value[n]` and `const char* value` bindgen translation

I'm still kind of new to Rust and know very little about C, but I need to get some bindings working from a C sdk.

There is a C type

typedef char uri[256];

and a C function definition

OpenDevice(const char* uri);

Now Rust bindgen translates the type into

pub type uri: [::std::os::raw::c_char; 256usize]

and the function definition into

pub fn OpenDevice(
    uri: *const ::std::os::raw::c_char
)

When I do the funtion call OpenDevice(uri) I get the error

mismatched types
expected raw pointer `*const i8`
         found array `[i8; 256]`

First of all, I don't understand why the compiler wants an i8. Is the ::std::os::raw::c_char treated as an i8?
And then, where did the char array go in the function definition?
In genral, I'm just lost! :smile:
Any help appreciated!

Both translations are correct. C has implicit array to pointer decay, but Rust doesn't. In Rust you need to reference the array with & or take a pointer with as_ptr().

char does not exist in Rust as a concept. c_char is an alias for u8 or i8 depending on the platform and that's how the compiler sees it.

8 Likes

You need to read the documentation.

It didn't go anywhere. There was no array in the function declaration to begin with. Even in the original C declaration, the function takes a pointer, not an array. (It's not possible for a C function to take an array by-value, anyway. Unlike in a regular variable declaration, an array argument in a function signature means a pointer.)

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.