在 Rust 中将原始指针转换为 16 位 Unicode 字符到文件路径 [英] Converting raw pointer to 16-bit Unicode character to file path in Rust
问题描述
我正在用一个用 Rust 编写的 DLL 替换一个用 C++ 编写的 DLL.目前DLL中的函数调用如下:
I'm replacing a DLL written in C++ with one written in Rust. Currently the function in the DLL is called as follows:
BOOL calledFunction(wchar_t* pFileName)
我相信在这种情况下 wchar_t
是一个 16 位 Unicode 字符,所以我选择在我的 Rust DLL 中公开以下函数:
I believe that in this context wchar_t
is a 16-bit Unicode character, so I chose to expose the following function in my Rust DLL:
pub fn calledFunction(pFileName: *const u16)
将原始指针转换为我实际上可以用来从 Rust DLL 打开文件的内容的最佳方法是什么?
What would be the best way to convert that raw pointer to something I could actually use to open the file from the Rust DLL?
推荐答案
以下是一些示例代码:
use std::ffi::OsString;
use std::os::windows::prelude::*;
unsafe fn u16_ptr_to_string(ptr: *const u16) -> OsString {
let len = (0..).take_while(|&i| *ptr.offset(i) != 0).count();
let slice = std::slice::from_raw_parts(ptr, len);
OsString::from_wide(slice)
}
// main example
fn main() {
let buf = vec![97_u16, 98, 99, 100, 101, 102, 0];
let ptr = buf.as_ptr(); // raw pointer
let string = unsafe { u16_ptr_to_string(ptr) };
println!("{:?}", string);
}
在u16_ptr_to_string
中,你做了三件事:
- 通过使用
偏移
(不安全) - 使用
from_raw_parts
<创建切片/a>(不安全) - 使用
from_wide
- get the length of the string by counting the non-zero characters using
offset
(unsafe) - create a slice using
from_raw_parts
(unsafe) - transform this
&[u16]
into anOsString
withfrom_wide
最好使用 wchar_t
和 wcslen
来自 libc 板条箱并使用另一个板条箱进行转换.重新实现已经在 crate 中维护的东西可能是个坏主意.
It is better to use wchar_t
and wcslen
from the libc crate and use another crate for conversion. This is maybe a bad idea to reimplement something that is already maintained in a crate.
这篇关于在 Rust 中将原始指针转换为 16 位 Unicode 字符到文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!