I am working with a c api with automatically generated bindings by Bindgen. One of the property structs defined by the rust wrapper takes a [i8, 256], which needs to be a string such as "mystr"
The C declaration is something like this:
typedef struct Properties
{
...
/** Vendor name used to identify specific hardware requested */
char name[MAX_NAME];
...
}
The binding that Bindgen creates looks like this:
pub struct Properties
{
...
pub name: [::std::os::raw::c_char; 256usize],
...
}
My code needs to fill this field somehow. I experimented with something like this:
//property.name is of type [i8; 256]
property.name = *("myName".as_bytes()) as [i8; 256];
which results in an error like this:
non-primitive cast: `[u8]` as `[i8; 256]`
an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
This should probably actually be something more like a string copy function. My current solution which seems to work, but isn't very clean, is defining a function to loop through the slice and put its characters into the array one by one. There has to be a better way to do this :
pub fn strcpy_to_arr_i8(out_arr: &[i8; 256], in_str: &str) -> Result<(), SimpleError> {
if in_str.len() > 256 {
bail!("Input str exceeds output buffer size.")
}
for (i, c) in in_str.chars().enumerate() {
out_arr[i] = c as i8;
}
Ok(())
}