如何将 Windows OsString 转换为 CString?

How can I convert a Windows OsString to a CString?

我在 Windows 上有一个 std::ffi::OsString,但我需要将一个 std::ffi::CString 传递给 FFI 函数。有什么方法可以将 OsString 转换为 CString 吗?

我知道在 Windows 上,OsString 由 WTF-8 编码缓冲区支持。基本上所有需要发生的事情就是附加一个 ASCII nul 字符并从中创建一个 CString。有什么好办法吗?如果没有,是否可以直接访问该缓冲区?

这是一些示例代码:

extern "system" fn some_ffi(s: *mut c_char);

fn my_func(os_string: &OsString) {
    let c_string: CString = // ???

    some_ffi(c_string.as_raw())
}

在类 Unix 系统上,您可以通过 std::os::unix::ffi::OsStrExt::as_bytes. You can pass that slice directly to CString::new.

获取 OsStrOsString 的原始字节作为 &[u8]

在 Windows 上,您 无法 获取 OsStrOsString 的原始字节。 WTF-8 编码被认为是私有实现细节。唯一的保证是,如果字符串包含有效的 Unicode,则可以使用 OsStr::to_str or OsString::into_string. You can also convert the string back to potentially ill-formed UTF-16 with std::os::windows::ffi::OsStrExt::encode_wide.

在常数时间内将其转换为 strString

不直接访问原始字节的动机是几乎没有库期望字符串编码为 WTF-8。事实上,一些图书馆甚至可能不希望使用 UTF-8! (他们可能反而期望在 current "ANSI" code page.) If it turns out that the library doesn't expect UTF-8 strings, you should instead convert the potentially ill-formed UTF-16 string to the expected encoding using WideCharToMultiByte.

中编码的字符串