我如何在 *c_char 和 Vec<u8> 之间进行 memcpy
How can I memcpy between *c_char and Vec<u8>
我有一个 Vec<u8>
假装是一个大磁盘:
lazy_static! {
static ref DISK: Mutex<Vec<u8>> = Mutex::new(vec![0; 100 * 1024 * 1024]);
}
我的 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 {
// ?
}
使用 Cstring::from_raw(buf).into_bytes()
反之亦然(documentation) to convert buf
to/from byte slice, then copy_from_slice 将数据复制到 DISK
- 此函数内部使用 memcpy
使用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
}
我有一个 Vec<u8>
假装是一个大磁盘:
lazy_static! {
static ref DISK: Mutex<Vec<u8>> = Mutex::new(vec![0; 100 * 1024 * 1024]);
}
我的 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 {
// ?
}
使用 Cstring::from_raw(buf).into_bytes()
反之亦然(documentation) to convert buf
to/from byte slice, then copy_from_slice 将数据复制到 DISK
- 此函数内部使用 memcpy
使用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
}