https://github.com/emoon/cfixed-string
Pass Rust strings to C with potentially not needing heap allocation
https://github.com/emoon/cfixed-string
rust string
Last synced: about 1 year ago
JSON representation
Pass Rust strings to C with potentially not needing heap allocation
- Host: GitHub
- URL: https://github.com/emoon/cfixed-string
- Owner: emoon
- License: mit
- Created: 2021-09-11T05:20:50.000Z (almost 5 years ago)
- Default Branch: main
- Last Pushed: 2022-04-01T08:36:18.000Z (about 4 years ago)
- Last Synced: 2025-03-26T07:36:37.705Z (about 1 year ago)
- Topics: rust, string
- Language: Rust
- Homepage:
- Size: 10.7 KB
- Stars: 13
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
[](https://github.com/emoon/cfixed-string/actions?workflow=Rust)
[](https://crates.io/crates/cfixed-string)
[](https://docs.rs/cfixed-string)
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.
Usage
-----
```toml
# Cargo.toml
[dependencies]
cfixed-string = "1.0"
```
Example
-------
```rust
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
ffi_func(ffi_str.as_ptr());
// 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
ffi_func(ffi_str.as_ptr());
}
```