[][src]Crate c_vec

Library to interface with chunks of memory allocated in C.

It is often desirable to safely interface with memory allocated from C, encapsulating the unsafety into allocation and destruction time. Indeed, allocating memory externally is currently the only way to give Rust shared mut state with C programs that keep their own references; vectors are unsuitable because they could be reallocated or moved at any time, and importing C memory into a vector takes a one-time snapshot of the memory.

This module simplifies the usage of such external blocks of memory. Memory is encapsulated into an opaque object after creation; the lifecycle of the memory can be optionally managed by Rust, if an appropriate destructor closure is provided. Safety is ensured by bounds-checking accesses, which are marshalled through get and set functions.

There are three unsafe functions: the two constructors, and the unwrapping method. The constructors are unsafe for the obvious reason (they act on a pointer that cannot be checked inside the method), but into_inner() is somewhat more subtle in its unsafety. It returns the contained pointer, but at the same time destroys the CVec without running its destructor. This can be used to pass memory back to C, but care must be taken that the ownership of underlying resources are handled correctly, i.e. that allocated memory is eventually freed if necessary.


use c_vec::CVec;

let slice = &mut [0, 1, 2];
let ptr = slice.as_mut_ptr();
let cvec = unsafe { CVec::new(ptr, slice.len()) };
for elem in cvec.iter() {
    println!("=> {}", elem);



The type representing an 'unsafe' non-mutable foreign chunk of memory.


Iterator over CSlice.


The type representing an 'unsafe' mutable foreign chunk of memory.


Iterator over CSliceMut.


Mutable iterator over CSliceMut.


The type representing a foreign mutable chunk of memory.


Iterator over CVec.


Mutable iterator over CVec.