gpt4 book ai didi

windows - 将原始指针转换为 16 位 Unicode 字符到 Rust 中的文件路径

转载 作者:可可西里 更新时间:2023-11-01 14:41:08 29 4
gpt4 key购买 nike

我正在用一个用 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);
}

u16_ptr_to_string 中,你做了 3 件事:

  • 通过使用 offset 计算非零字符来获取字符串的长度(不安全)
  • 使用 from_raw_parts 创建切片(不安全)
  • 将此 &[u16] 转换为一个 OsStringfrom_wide

最好用wchar_twcslen从 libc crate 并使用另一个 crate 进行转换。重新实现已经在 crate 中维护的东西可能不是一个好主意。

关于windows - 将原始指针转换为 16 位 Unicode 字符到 Rust 中的文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48586816/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com