从FFI返回的片中创建OsStr(ing)的正确方法是什么? [英] What's the right way to create OsStr(ing) from a FFI-returned slice?

查看:94
本文介绍了从FFI返回的片中创建OsStr(ing)的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数接受带有参数data: *const u8, length: usize的回调,该回调表示某些路径.从中创建OsStr(ing)的正确方法是什么?

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?

OsStrExt中有一个from_byte_slice,但是似乎它不检查数据是否正确WTF-8或其他内容,并且不清楚如何使用它.

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.

推荐答案

您可以使用

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() {
}

请注意,这是特定于* nix的-Windows和* nix并不表示路径是相同的方式(结果这东西相当复杂!).如果您的API实际上返回的是UTF-8字符串,则可以使用普通的字符串方法将原始组件转换为&str,然后转换为OsStr(ring).

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

有关 WTF-8 的更多信息,我强烈推荐优秀的文档.

For further information about WTF-8, I highly recommend the excellent docs.

这篇关于从FFI返回的片中创建OsStr(ing)的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆