What's the right way to create OsStr(ing) from a FFI-returned slice?

大城市里の小女人 提交于 2019-12-13 14:33:41

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!