mbox
: malloc
-based box
This crate provides structures that wrap pointers returned from malloc
as a Box, and
automatically free
them on drop. These types allow you to interact with pointers and
null-terminated strings and arrays in a Rusty style.
Examples
extern crate libc;
extern crate mbox;
use ;
use MString;
// Assume we have a C function that returns a malloc'ed string.
unsafe extern "C"
Note: This crate does not support Windows in general.
Pointers in Rust are required to be aligned to be sound. However, there is no API on Windows that are both compatible with
free()
and supports aligned-malloc.Because the primary purpose of this crate is interoperability with C code working with
malloc()
, it is impossible for us to switch to the safe variant like_aligned_malloc()
(which requires_aligned_free()
).On Windows, trying to use
MBox<T>
orMArray<T>
withT
's alignment not equal to 1 will not compile.# ; use MBox; let value = new; // will not compile,
Installation
Add this to your Cargo.toml:
[]
= "0.7"
Usage
This crate provides three main types, all of which uses the system's malloc
/free
as the
allocator.
MBox<T>
— Similar toBox<T>
.MString
— Similar tostd::ffi::CString
.MArray<T>
— A null-terminated array, which can be used to represent e.g. array of C strings terminated by a null pointer.
#![no_std]
You may compile mbox
and disable the std
feature to not link to std
(it will still link to
core
.
[]
= { = "0.7", = false }
When #![no_std]
is activated, you cannot convert an MString
into a std::ffi::CStr
, as the
type simply does not exist 🙂.
Nightly
To use nightly-channel features (if you need support for custom dynamic-sized types), enable the
nightly
feature:
[]
= { = "0.7", = ["nightly"] }
Migrating from other crates
Note that MBox
does not support custom allocator. If the type requires custom allocation,
MBox
cannot serve you.
-
malloc_buf
—Malloc<T>
is equivalent toMBox<T>
. Note however thatMBox<[T]>::from_raw_parts
will not allow null, 0-length buffers; use a dangling pointer instead. -
cbox
— When not using a customDisposeRef
, theCSemiBox<'static, T>
type is equivalent toMBox<T>
, andCBox<T>
is equivalent to&'static T
. -
c_vec
— When usingfree
as the destructor,CVec<T>
is equivalent toMBox<[T]>
andCSlice<T>
as[T]
. -
malloced
—Malloced<T>
is equivalent toMBox<T>
. Note however thatmbox
depends onlibc
(more stable, but also longer build-time) and doesn't supportdyn Any
downcasting. -
malloc-array
—HeapArray<T>
is similar toMBox<T>
, but this crate focuses more on raw memory management.