问题
I have a function that accepts a callback with args data: *const u8, length: usize
, that represents some path. What is the right way to create an OsStr(ing) from this?
There's from_byte_slice
in OsStrExt
, but seems like it doesn't check if the data is correct WTF-8 or whatever, and it's not clear how to use it.
回答1:
You can use from_raw_parts to go from the raw pointer to a slice, then OsStrExt::from_bytes:
use std::slice;
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt; // NOTE PLATFORM-SPECIFIC
fn foo(data: *const u8, length: usize) {
let slice = unsafe { slice::from_raw_parts(data, length) };
let os_str = OsStr::from_bytes(slice);
}
fn main() {
}
Note that this is *nix-specific - Windows and *nix do not represent paths is the same way (turns out this stuff is reasonably complicated!). If your API actually is returning a UTF-8 string, then you could use the normal string methods to convert the raw components to a &str
and then to an OsStr(ring)
.
For further information about WTF-8, I highly recommend the excellent docs.
来源:https://stackoverflow.com/questions/28515784/whats-the-right-way-to-create-osstring-from-a-ffi-returned-slice