I have a function
extern "C" {
fn log_impl(ptr: *const u8);
}
fn log(s: &str) {
log_impl(s.as_bytes() as *const u8);
}
This gives me the following error:
error[E0606]: casting `&[u8]` as `*const u8` is invalid
--> src/main.rs:6:14
|
6 | log_impl(s.as_bytes() as *const u8);
| ^^^^^^^^^^^^^^^^^^^^^^^^^
The most similar question to what I'm trying to do is Converting a str to a &[u8].
Click the File tab. Do one of the following: To convert the document without saving a copy, click Info, and then click Convert. To create a new copy of the document in Word 2016 or Word 2013 mode, click Save As, and then choose the location and the folder where you want to save the new copy.
Rust strings are not NUL-terminated like most C functions expect. You can convert a &str
to *const u8
by using &s.as_bytes()[0] as *const u8
or by using s.as_ptr()
, but that will not be valid to pass to any C function expecting a NUL-terminated string.
Instead, you probably need to use CString
which will copy the string to a buffer and add a NUL terminator to the end. Here is an example assuming that log_impl
doesn't store a pointer to the string:
fn log(s: &str) {
unsafe {
let c_str = CString::new(s).unwrap();
log_impl(c_str.as_ptr() as *const u8);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With