let raw_ptrs: Vec<*const c_char> = c_strs.iter().map(|cs| cs.as_ptr()).collect();
raw_ptrs.into_boxed_slice()
}
code
let raw_ptrs = str_to_c_chars(DEVICE_EXTENSIONS.to_vec());
for &ptr in raw_ptrs.iter() {
let c_str = unsafe { std::ffi::CStr::from_ptr(ptr) };
let str_slice = c_str.to_str().expect("CStr::to_str failed");
println!("{}", str_slice);
}
I get the error: CStr::to_str failed: Utf8Error { valid_up_to: 0, error_len: Some(1) }
They should be identical, right?
Assistant
User
Is there any other way to do this? Returning both the strings and pointers to them seems excessive
Assistant
The issue you're encountering is related to the difference in lifetime management and ownership between the first and the second piece of code. Specifically, the problem lies in the scope and how the lifetimes of CString objects are managed.
Explanation:
In your first code block, the c_strs vector lives in the same scope as the raw_ptrs vector. The CString objects in c_strs are kept alive for the entire duration of the for loop over raw_ptrs.
rust
let c_strs: Vec<_> = DEVICE_EXTENSIONS.iter().map(|&str| CString::new(str).unwrap()).collect();
let raw_ptrs: Vec<*const c_char> = c_strs.iter().map(|cs| cs.as_ptr()).collect();
for &ptr in raw_ptrs.iter() {
let c_str = unsafe { std::ffi::CStr::from_ptr(ptr) };
let str_slice = c_str.to_str().expect("CStr::to_str failed");
println!("{}", str_slice);
}
Because c_strs lives long enough, the pointers in raw_ptrs remain valid.
Issue in the Second Code Block:
In the second code block, when you invoke str_to_c_chars, the c_strs vector of CString objects is created within the function scope and then discarded when the function returns, leaving the raw_ptrs with dangling pointers.
Since the c_strs vector goes out of scope as soon as the function returns, the pointers in raw_ptrs point to invalid memory. Consequently, when you try to dereference those pointers, you're accessing memory that has already been freed, leading to undefined behavior and the Utf8Error.
Solution:
To fix this, you need to ensure that the CString objects' lifetimes are properly tied to the usage of their raw pointers. One way to achieve this is to return both the c_strs and raw_ptrs from the function:
rust
fn str_to_c_chars(s: Vec<&str>) -> (Box<[CString]>, Box<[*const c_char]>) {
let c_strs: Vec<CString> = s.iter().map(|&str| CString::new(str).unwrap()).collect();
let raw_ptrs: Vec<*const c_char> = c_strs.iter().map(|cs| cs.as_ptr()).collect();
(c_strs.into_boxed_slice(), raw_ptrs.into_boxed_slice())
}
fn main() {
let (c_strs, raw_ptrs) = str_to_c_chars(DEVICE_EXTENSIONS.to_vec());
for &ptr in raw_ptrs.iter() {
let c_str = unsafe { std::ffi::CStr::from_ptr(ptr) };
let str_slice = c_str.to_str().expect("CStr::to_str failed");
println!("{}", str_slice);
}
}
In this modified function, the c_strs vector (containing CString objects) remains in scope for as long as the raw_ptrs are needed, thus ensuring that the pointers remain valid.
Yes, returning both the strings and pointers can feel excessive. There are a few alternative approaches you can take that avoid this redundancy:
1. Maintaining Ownership in the Main Function
You can keep the creation of CString objects in the main function and only return the raw pointers:
rust
fn str_to_c_chars<'a>(s: Vec<&str>, buffer: &'a mut Vec<CString>) -> Box<[*const c_char]> {
buffer.extend(s.iter().map(|&str| CString::new(str).unwrap()));
let raw_ptrs: Vec<*const c_char> = buffer.iter().map(|cs| cs.as_ptr()).collect();
raw_ptrs.into_boxed_slice()
}
fn main() {
let mut c_strs = Vec::new();
let raw_ptrs = str_to_c_chars(DEVICE_EXTENSIONS.to_vec(), &mut c_strs);
for &ptr in raw_ptrs.iter() {
let c_str = unsafe { std::ffi::CStr::from_ptr(ptr) };
let str_slice = c_str.to_str().expect("CStr::to_str failed");
println!("{}", str_slice);
}
}
Here, the buffer (c_strs vector) is passed to the function to maintain the CString objects.
2. Using a Struct to Maintain Ownership
You can encapsulate both the CString objects and their raw pointers inside a struct:
rust
struct CStringPtrs {
c_strs: Box<[CString]>,
raw_ptrs: Box<[*const c_char]>,
}
fn str_to_c_chars(s: Vec<&str>) -> CStringPtrs {
let c_strs: Vec<CString> = s.iter().map(|&str| CString::new(str).unwrap()).collect();
let raw_ptrs: Vec<*const c_char> = c_strs.iter().map(|cs| cs.as_ptr()).collect();
CStringPtrs {
c_strs: c_strs.into_boxed_slice(),
raw_ptrs: raw_ptrs.into_boxed_slice(),
}
}
fn main() {
let cstring_ptrs = str_to_c_chars(DEVICE_EXTENSIONS.to_vec());
for &ptr in cstring_ptrs.raw_ptrs.iter() {
let c_str = unsafe { std::ffi::CStr::from_ptr(ptr) };
let str_slice = c_str.to_str().expect("CStr::to_str failed");
println!("{}", str_slice);
}
}
This method keeps the CString objects within a struct, ensuring they outlive the raw pointers.
3. Returning a Single Boxed Slice of Raw Pointers, with Lifetimes Managed by the Function
Another way is to modify the function signature to accept a reference to maintain scope without having to return both:
rust
fn str_to_c_chars<'a>(s: Vec<&str>, buffer: &'a mut Vec<CString>) -> Box<[*const c_char]> {
buffer.extend(s.iter().map(|&str| CString::new(str).unwrap()));
let raw_ptrs: Vec<*const c_char> = buffer.iter().map(|cs| cs.as_ptr()).collect();
raw_ptrs.into_boxed_slice()
}
fn main() {
let mut c_strs = Vec::new();
let raw_ptrs = str_to_c_chars(DEVICE_EXTENSIONS.to_vec(), &mut c_strs);
for &ptr in raw_ptrs.iter() {
let c_str = unsafe { std::ffi::CStr::from_ptr(ptr) };
let str_slice = c_str.to_str().expect("CStr::to_str failed");
println!("{}", str_slice);
}
}
This makes it clear that the CString objects are managed by the caller and addresses the need to ensure their lifespan matches the raw pointers'.
Summary:
Choose the approach that meets your needs for simplicity and clarity. Using a struct is often a clean way to encapsulate related data, but passing a mutable buffer can also be an effective solution to manage lifetimes without returning multiple values.