First of all, char
in Rust is not the equivalent to a char
in C:
The char
type represents a single character. More specifically, since 'character' isn't a well-defined concept in Unicode, char
is a 'Unicode scalar value', which is similar to, but not the same as, a 'Unicode code point'.
In Rust you may use u8
or i8
depending in the operating system. You can use std::os::raw::c_char
for this:
Equivalent to C's char
type.
C's char
type is completely unlike Rust's char
type; while Rust's type represents a unicode scalar value, C's char
type is just an ordinary integer. This type will always be either i8
or u8
, as the type is defined as being one byte long.
C chars are most commonly used to make C strings. Unlike Rust, where the length of a string is included alongside the string, C strings mark the end of a string with the character '\0'
. See CStr
for more information.
First, we need a variable, which can be passed to the function:
let mut ptr: *const c_char = std::mem::uninitialized();
To pass it as *mut
you simply can use a reference:
get_string(&mut ptr);
Now use the *const c_char
for creating a CStr
:
let c_str = CStr::from_ptr(ptr);
For converting it to a String
you can choose:
c_str.to_string_lossy().to_string()
or
c_str().to_str().unwrap().to_string()
However, you shouldn't use String
if you don't really need to. In most scenarios, a Cow<str>
fulfills the needs. It can be obtained with c_str.to_string_lossy()
:
If the contents of the CStr
are valid UTF-8 data, this function will return a Cow::Borrowed([&str])
with the the corresponding [&str]
slice. Otherwise, it will replace any invalid UTF-8 sequences with U+FFFD REPLACEMENT CHARACTER
and return a Cow::[Owned](String)
with the result.
You can see this in action on the Playground. This Playground shows the usage with to_string_lossy()
.