我怎样才能在*c_char和Vec <u8>之间进行记忆

Ric*_*ich 1 ffi rust

我有一个Vec<u8>假装是一个大磁盘:

lazy_static! {
    static ref DISK: Mutex<Vec<u8>> = Mutex::new(vec![0; 100 * 1024 * 1024]);
}
Run Code Online (Sandbox Code Playgroud)

我的Rust代码(直接从C调用)有一些函数可以读写这个磁盘,但我不明白我在那些函数中编写的内容是为了在磁盘和C调用者之间进行memcpy(或者是否Vec是最好的结构在这里使用):

extern "C" fn pread(
    _h: *mut c_void,
    buf: *mut c_char,
    _count: uint32_t,
    offset: uint64_t,
    _flags: uint32_t,
) -> c_int {
    // ?
}

extern "C" fn pwrite(
    _h: *mut c_void,
    buf: *const c_char,
    _count: uint32_t,
    offset: uint64_t,
    _flags: uint32_t,
) -> c_int {
    // ?
}
Run Code Online (Sandbox Code Playgroud)

Fra*_*gné 5

使用std::ptr::copy_nonoverlapping.

use std::ptr;

// Copy from disk to buffer
extern "C" unsafe fn pread(
    _h: *mut c_void,
    buf: *mut c_char,
    count: uint32_t,
    offset: uint64_t,
    _flags: uint32_t,
) -> c_int {
    // TODO: bounds check
    ptr::copy_nonoverlapping(&DISK.lock()[offset], buf as *mut u8, count);
    count
}
Run Code Online (Sandbox Code Playgroud)