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 introduction forms, and the pointer elimination form. The introduction forms are unsafe for the obvious reason (they act on a pointer that cannot be checked inside the method), but the elimination form is somewhat more subtle in its unsafety. By using a pointer taken from a c_vec::t without keeping a reference to the c_vec::t itself around, the c_vec could be garbage collected, and the memory within could be destroyed. There are legitimate uses for the pointer elimination form -- for instance, to pass memory back into C -- but great care must be taken to ensure that a reference to the c_vec::t is still held if needed.
c_vec
- The type representing a foreign chunk of memoryc_vec
- Create a c_vec
from a foreign buffer with a given length.c_vec_with_dtor
- Create a c_vec
from a foreign buffer, with a given length, and a function to run upon destruction.get
- Retrieves an element at a given indexlen
- Returns the length of the vectorptr
- Returns a pointer to the first element of the vectorset
- Sets the value of an element at a given indexc_vec
The type representing a foreign chunk of memory
Wrapped in a enum for opacity; FIXME #818 when it is possible to have truly opaque types, this should be revisited.
c_vec_({base: *mut T, len: uint, rsrc: @dtor_res,})
c_vec
unsafe fn c_vec<T>(base: *mut T, len: uint) -> c_vec<T>
Create a c_vec
from a foreign buffer with a given length.
c_vec_with_dtor
unsafe fn c_vec_with_dtor<T>(base: *mut T, len: uint, dtor: fn@()) -> c_vec<T>
Create a c_vec
from a foreign buffer, with a given length, and a function to run upon destruction.
get
fn get<T: copy>(t: c_vec<T>, ofs: uint) -> T
Retrieves an element at a given index
Fails if ofs
is greater or equal to the length of the vector
len
fn len<T>(t: c_vec<T>) -> uint
Returns the length of the vector
ptr
unsafe fn ptr<T>(t: c_vec<T>) -> *mut T
Returns a pointer to the first element of the vector
set
fn set<T: copy>(t: c_vec<T>, ofs: uint, v: T)
Sets the value of an element at a given index
Fails if ofs
is greater or equal to the length of the vector