我正在用 Rust 编写的 DLL 替换用 C++ 编写的 DLL。
目前DLL中的函数调用如下:
BOOL calledFunction(wchar_t* pFileName)
我相信在这样的背景下wchar_t
是一个 16 位 Unicode 字符,所以我选择在 Rust DLL 中公开以下函数:
pub fn calledFunction(pFileName: *const u16)
将原始指针转换为我实际上可以用来从 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);
}
In u16_ptr_to_string
,你做了三件事:
- 通过计算非零字符来获取字符串的长度offset https://doc.rust-lang.org/std/primitive.pointer.html#method.offset(不安全)
- 使用创建一个切片from_raw_parts https://doc.rust-lang.org/std/slice/fn.from_raw_parts.html(不安全)
- 改变这个
&[u16]
进入一个OsString
with from_wide https://doc.rust-lang.org/std/os/windows/ffi/trait.OsStringExt.html#tymethod.from_wide
最好使用wchar_t https://docs.rs/libc/0.2.36/libc/type.wchar_t.html and wcslen https://docs.rs/libc/0.2.36/libc/fn.wcslen.html从 libc crate 中获取并使用另一个 crate 进行转换。重新实现已经在板条箱中维护的东西可能是一个坏主意。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)