首页 > 解决方案 > 如何在 *c_char 和 Vec 之间进行 memcpy

问题描述

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

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

我的 Rust 代码(直接从 C 调用)有一些函数可以读取和写入这个磁盘,但我不明白我会在这些函数中写什么来 memcpy 在磁盘和 C 调用者之间(或者如果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 {
    // ?
}

标签: rustffi

解决方案


使用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
}

推荐阅读