-
Notifications
You must be signed in to change notification settings - Fork 13.8k
Closed
Description
I am looking to do something like the following:
pub unsafe fn validate_str_mut<'a>(str_ptr: *mut c_char, _str_max: usize) -> Result<(&'a mut [u8]), ()> {
if str_ptr.is_null() {
return Err(());
}
// Make sure that we can convert from a C string
// to a Rust &u8
let cur_str: &CStr = CStr::from_ptr(str_ptr);
let new_str: &mut [u8] = cur_str.to_bytes().as_mut();
Ok(new_str)
}
However, that returns the following error:
error[E0596]: cannot borrow immutable borrowed content as mutable
--> jims_uri\src\lib.rs:499:34
|
499 | let new_str: &mut [u8] = cur_str.to_bytes().as_mut();
| ^^^^^^^^^^^^^^^^^^ cannot borrow as mutable
I don't see a way to do anything like the following:
let cur_str: &mut CStr = CStr::from_ptr(str_ptr);
The intent is to allocate the memory in the C++ code, and simply allow Rust to populate it. Ideally I could use _str_max to let Rust know the size so that it wouldn't exceed the allocation.
I am starting to think that I will need to reverse the logic where I allocate the string in Rust, but then I need extra calls from C++ to deallocate it.
Note that the following works for a const string
pub unsafe fn validate_str<'a>(str_ptr: *const c_char) -> Result<(&'a [u8]), ()> {
if str_ptr.is_null() {
return Err(());
}
// Make sure that we can convert the URI from a C string
// to a Rust &str
let cur_str: &CStr = CStr::from_ptr(str_ptr);
let new_str = cur_str.to_bytes();
Ok(new_str)
}
Any advice is appreciated.
Thanks,
-Dave
Metadata
Metadata
Assignees
Labels
No labels