Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a &str to a *const u8? [duplicate]

Tags:

rust

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].

like image 432
War Donkey Avatar asked Mar 09 '18 23:03

War Donkey


People also ask

How do you convert in Word?

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.


1 Answers

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);
    }
}
like image 194
Jordan Miner Avatar answered Sep 27 '22 18:09

Jordan Miner