小编Tup*_*per的帖子

从String到*const i8的正确方法是什么?

在我为Cassandra C++驱动程序编写安全包装器的持续传奇中,当我使用以下签名调用C函数时,我的眼睛现在转向避免内存泄漏:

cass_string_init2(const char* data, cass_size_t length);
Run Code Online (Sandbox Code Playgroud)

要么

cass_string_init(const char* null_terminated);
Run Code Online (Sandbox Code Playgroud)

我尝试了一些名义上有效的方法,并产生了正确的结果,但我还没有找到一种方法来正确管理这些数据的生命周期.以下是两种示例方法.

pub fn str_to_ref(mystr:&str) -> *const i8 {unsafe{
    let cstr = CString::from_slice(mystr.as_bytes());
    cstr.as_slice().as_ptr()
}}
Run Code Online (Sandbox Code Playgroud)

pub fn str_to_ref(mystr: &str) -> *const i8 {
    let l = mystr.as_bytes();
    unsafe {
        let b = alloc::heap::allocate(mystr.len()+1, 8);
        let s = slice::from_raw_parts_mut(b, mystr.len()+1);
        slice::bytes::copy_memory(s, l);
        s[mystr.len()] = 0;
        return b as *const i8;
    }
}
Run Code Online (Sandbox Code Playgroud)

第一个做无效的内存访问,如

==26355==  Address 0x782d140 is 0 bytes inside a block of size 320 free'd …
Run Code Online (Sandbox Code Playgroud)

ffi rust

8
推荐指数
1
解决办法
3865
查看次数

有没有办法获取 Vec<T> 的可变子切片的引用?

我想预先分配一个向量,然后写入它的切片,包括从 a 写入它TcpStream,它以 abuf: &mut [u8]作为参数。

// Create a vec with 256MB capacity
let mut myvec: Vec<u8> = Vec::with_capacity(268435456);

// Grow the vec to 256MB and initialize it with zeroes 
myvec.resize(268435456, 0x00);

// Try to get a mutable slice of the first 1kb of the vec
let body_slice: &mut [u8] = myvec[10..1034];
Run Code Online (Sandbox Code Playgroud)
// Create a vec with 256MB capacity
let mut myvec: Vec<u8> = Vec::with_capacity(268435456);

// Grow the vec to 256MB and initialize it with …
Run Code Online (Sandbox Code Playgroud)

slice rust

7
推荐指数
1
解决办法
4230
查看次数

标签 统计

rust ×2

ffi ×1

slice ×1