我怎样才能* c_char和血管内皮细胞之间的memcpy的

问题描述 投票:1回答:2

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

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

我锈代码(由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 {
    // ?
}
rust ffi
2个回答
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
}

1
投票

使用Cstring::from_raw(buf).into_bytes()反之亦然(documentation)至buf从字节切片转换到/,然后copy_from_slice复制数据到DISK - 这个函数使用的memcpy内部

© www.soinside.com 2019 - 2024. All rights reserved.