Is there a way to convert Vec<u8> to OSstring?

Use the following method, but compile failed...:

use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
let testStr = String::from("test").as_str().as_bytes().to_vec();
let retStringExt = OsString::from_vec(testStr);

got error:

error[E0599]: no function or associated item named from_vec found for type std::ffi::OsString in the current scope
373 | let retStringExt = OsString::from_vec(testStr);
| ^^^^^^^^ function or associated item not found in std::ffi::OsString

Unfortunately there's no cross-platform way to turn a bunch of bytes (Vec<u8>) into an OsString because not all operating systems represent strings using a bunch of bytes.

On Windows, strings are represented using Unicode (roughly UTF-16), you can use std::os::windows::ffi::OsStringExt to convert a &[u16] into an OsString.

Operating systems descended from Unix do use an opaque sequence of bytes (Vec<u8>) to represent strings, so the from_vec() method from std::os::unix::ffi::OsStringExt can be used to convert between Vec<u8> and OsString.

Also keep in mind that you need to import these traits (i.e. use std::os::windows::ffi::OsStringExt) to get access to their functionality.

Windows uses ill-formed utf16 as string, and the rust Command's output is Vec<u8> (byte stream), i think but i am not sure that it is utf16 encoded string, so, i want to convert it to OSstring. If i use String::from_utf8 to convert the returned byte stream (Vec<u8>) to UTF8 string, it is wrong.
And windows uses function 'MultiByteToWideChar' to convert byte stream to UTF16, but in rust i could not find any function to do it.

I found a library local_encoding contains this function ''MultiByteToWideChar' and it works well!

This SO post looks relevant, if a little old: How do I read OS-compatible strings from stdin?

1 Like

Yes! local_encoding does a simple wrap~!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.