rust - 如何在 *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 {
// ?
}
解决方案
使用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
}
推荐阅读
- css - Font Awesome 5 图标未在 Chrome 上的 :before 元素中呈现
- javascript - Whats the best way to check for the existence of a document which contains a field with a specific value - Firestore?
- javascript - JavaScript 箭头函数是如何工作的?
- json - 如何缩短类中变量的声明?
- mysql - Mysql group by 与 group by 相反
- excel - 将每个数据行保存在单独的新 CSV 文件中
- c++ - 共享预编译头文件
- java - 如何使用 Java 中的嵌套循环打印返回 2x2 和 3x3 矩阵中的字符串值的数学乘法表
- c# - ASP.NET Core 3.1 SHA512 和 SHA256Managed 有什么区别
- django - 无法重定向到类别列表 url - django