Rust string to *char


#1

If there platform-independent way of converting String/&str to c-style string and obtaining memory address?

So far I’ve got this, but it requires os-specific extension.

use std::os::unix::ffi::OsStrExt;

let s:String = "abc".to_string();
let c_str = (OsString::from(&s).as_os_str().as_bytes()).as_ptr();

I’m running it in unsafe block anyway


#2

Other platforms don’t have this because they may not be char – e.g. Windows uses wide characters. I think you want CStr::to_bytes() instead. Or even better, go directly to CStr::as_ptr().


#3

And how will I get Cstr from String/&str? I am starring at he docs and don’t see anything helpful there.


#4

It will have to be an allocated CString, since it needs to ensure there’s a ‘\0’ at the end. CString::new() can convert from both String and &str. Having allocation is not nice for static probes though, so a pointer and length pair would be preferable. Or with probe “semaphore” support, you could gate the heavier argument preparation to only trigger when probes are in use.


#5

I’ve got pointer+length working (you can get that from passing &string). Having c string would be convenient though, since every tool out there can use that. I’d like to add support for rust string to bcc and stap,but still c string is nice-to-have.