How can I index C arrays in Rust?

2019-02-25 14:11发布

问题:

I have a C function returning a pointer:

type MYSQL_RES_REF = *mut c_void;
type MYSQL_ROW = *const *const c_char;

#[no_mangle]
extern "C" {
    fn mysql_fetch_row(res: MYSQL_RES_REF) -> MYSQL_ROW;
}

let pointer = mysql_fetch_row(self.res);
let row_p = match pointer {
    p if p == (0 as *const *const c_char) => panic!(),
    p => p,
};

let field: &[u8] = unsafe { ffi::c_str_to_bytes(row_p[i]) };

but attempting to index it (the last line) results in an error:

error: cannot index a value of type `*const *const i8`

I wonder if std::c_vec was what I wanted, but apparently that has been removed.

回答1:

There is an offset method on pointers which can be used as:

let new_p = p.offset(i);

to get a pointer i elements away from the current one. It is not bounds-checked, obviously, so you must ensure it stays within the bounds (or one-past-the-end).


There is also an unstable offset intrinsic.



标签: arrays rust ffi