#string #heap-allocation #pass #needing #short #byte #buffer


Pass Rust strings to C with potentially not needing heap allocation

1 stable release

1.0.0 Sep 11, 2021

#497 in Memory management

47 downloads per month
Used in bgfx-rs

MIT license

262 lines

Build Status Crates.io Documentation

cfixed-string is used for passing Rust string to C with potentially not needing to do a heap allocation.

A problem with using the standard library CString is that it will always allocate memory on the heap even if the string you are trying to use is very short. This can cause performance issues and potentially adding to memory fragmentation depending on your system.

CFixedString will instead have a 512 byte buffer on the stack that can then be used when calling the FFI function. This allows strings that are less than 512 characters (including zero termination) to be on the stack instead of the heap which removes the need for memory allocation and free. In case the string is larger it will fallback to CString from the standard library.


# Cargo.toml
cfixed-string = "1.0"


use cfixed_string::CFixedString;

fn main() {
	// Create a string that will be stored on the stack
	let ffi_str = CFixedString::from_str("test");
	// And pass it to the FFI function

	// It's also possible to format a string directly on the stack if it fits using the format_c macro
	let fmt_str = format_c!("hello {}", 123);
	// And pass it to the FFI function

No runtime deps