我有以下代码:
use bindings::Windows::Win32::DisplayDevices::POINT;
use bindings::Windows::Win32::Gdi::{GetPixel, GetWindowDC, HDC};
use bindings::Windows::Win32::SystemServices::{BOOL, PSTR};
use bindings::Windows::Win32::WindowsAndMessaging::{self, FindWindowA, HWND};
use std::ffi::CString;
fn main() {
let mut window_name_2 = "Window Title";
let hwnd;
unsafe { hwnd = FindWindowA(std::ptr::null_mut(), window_name_2) }
}
它产生错误:
bindings::Windows::Win32::WindowsAndMessaging
pub unsafe fn FindWindowA<'a, T0__, T1__>(lpclassname: T0__, lpwindowname: T1__) -> HWND
where
T0__: ::windows::IntoParam<'a, super::superSystemServices::PSTR>,
T1__: ::windows::IntoParam<'a, super::superSystemServices::PSTR>,
the trait bound `*mut _: windows::traits::into_param::IntoParam<'_, PSTR>` is not satisfied
the trait `windows::traits::into_param::IntoParam<'_, PSTR>` is not implemented for `*mut _`rustcE0277
main.rs(1, 1): required by a bound in this
windows.rs(311, 23): required by this bound in `FindWindowA`
我不明白这意味着什么或如何解决它。
答案 0 :(得分:1)
windows-rs 包的 0.8.0 版改用 impl Trait
,使签名更易于阅读,同时也简化了错误诊断。
鉴于问题中的代码,错误消息现在显示为:
error[E0277]: the trait bound `*mut _: IntoParam<'_, PSTR>` is not satisfied
--> src\main.rs:11:21
|
11 | unsafe { hwnd = FindWindowA(std::ptr::null_mut(), window_name_2) }
| ^^^^^^^^^^^ the trait `IntoParam<'_, PSTR>` is not implemented for `*mut _`
|
::: C:\...\target\debug\build\findwindow_test-67a9095d9a724f24\out/windows.rs:129:27
|
129 | pub unsafe fn FindWindowA<'a>(
| ----------- required by a bound in this
130 | lpclassname: impl ::windows::IntoParam<'a, super::SystemServices::PSTR>,
| ----------------------------------------------------- required by this bound in `FindWindowA`
潜在问题仍然与以前相同(见下文):IntoParam
特征未针对所涉及的类型组合实现。之前的解决方案(见下文)仍然有效,尽管 0.8.0 版还引入了一个 NULL
常量,因此以下解决方案同样有效:
unsafe { hwnd = FindWindowA(PSTR::NULL, window_name_2) }
GitHub 存储库还引入了一个 FAQ,其中包含有关此特定主题的条目 (How do I read the signatures of generated functions and methods? What's with IntoParam
?)
真正的错误信息更有启发性:
error[E0277]: the trait bound `*mut _: IntoParam<'_, PSTR>` is not satisfied
--> src\main.rs:11:21
|
11 | unsafe { hwnd = FindWindowA(std::ptr::null_mut(), window_name_2) }
| ^^^^^^^^^^^ the trait `IntoParam<'_, PSTR>` is not implemented for `*mut _`
|
::: C:\...\target\debug\build\findwindow_test-805b35ca49628608\out/windows.rs:117:27
|
117 | pub unsafe fn FindWindowA<
| ----------- required by a bound in this
118 | 'a,
119 | T0__: ::windows::IntoParam<'a, super::SystemServices::PSTR>,
| ----------------------------------------------------- required by this bound in `FindWindowA`
它告诉你哪个参数不符合要求,即T0__
,第一个。无法实现 IntoParam 特性将 *mut _
转换为 PSTR
。 IntoParam
trait 的目的是允许在 Rust 类型(如 &str
)和 ABI 类型(如 PSTR
)之间方便地转换。
为了解决这个问题,你可以构造一个默认的 PSTR
代替,即
unsafe { hwnd = FindWindowA(PSTR::default(), window_name_2) }
PSTR
(目前)住在Windows::Win32::SystemServices
。