windows - 如何将OsString传递给Win32 API调用

标签 windows winapi rust

我使用了xxxA版本的调用来使用CString编写此代码。现在,我想使用xxxW版本,无法解决如何将OsString传递给调用的问题。

let cname = OsString::from("my backend class");
let brush = CreateSolidBrush(RGB(0, 0, 0));
let cl = WNDCLASSW {
    style: 0,
    lpfnWndProc: Some(callback),
    cbClsExtra: 0,
    cbWndExtra: std::mem::size_of::<&i32>() as i32,
    hInstance: handle,
    hIcon: 0 as HICON,
    hCursor: LoadCursorW(std::ptr::null_mut(), IDC_ARROW),
    hbrBackground: brush, //(COLOR_WINDOW + 1) as HBRUSH,
    lpszMenuName: 0 as LPWSTR,
    lpszClassName: cname.as_ptr(), <<<=======
};
OsString没有as_ptr()方法。我不应该使用OsString吗?如果没有,我应该怎么用?

最佳答案

the documentation:

On Windows, OsStr implements the std::os::windows::ffi::OsStrExt trait, which provides an encode_wide method. This provides an iterator that can be collected into a vector of u16.


encode_wide 的文档还指出:

Note that the encoding does not add a final null terminator.


因此:
use std::os::windows::ffi::OsStrExt;

let cname = OsStr::new("my backend class")
    .encode_wide()
    .chain(Some(0)) // add NULL termination
    .collect::<Vec<_>>();

// and then call cname.as_ptr() as you are currently doing

关于windows - 如何将OsString传递给Win32 API调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64175598/

相关文章:

windows - 如何在 Windows 上访问 $PWD 变量?

c++ - LoadLibrary A 在哪里寻找文件?

rust - 为什么在 "as_slice"的情况下引用的生命周期不够长?

c# - 如何从 SessionID 获取 Windows 用户名?

c++ - 如何在 Windows 7 上获取 gethostid 行为?

c - 在 C 中检索 Windows 进程的完整列表

c++ - 显示 MessageBox 后子窗口失去焦点

c++ - 如何使用GetNamedSecurityInfo?

rust - 当poll_read的缓冲区大小不足以容纳我的缓冲区时该怎么办?

rust - 编译 rust-src 时未知功能 `llvm_asm`