【问题标题】:Why does calling SystemParametersInfo from Rust to set the wallpaper set it to black?为什么从 Rust 调用 SystemParametersInfo 将壁纸设置为黑色?
【发布时间】:2019-11-25 11:12:23
【问题描述】:

我正在尝试使用 winapi crate 和 SystemParametersInfo 在 Rust 中设置 Windows 背景,但它将背景设置为黑色。在 C++ 中,这通常意味着 pvParam 未正确传递或类型错误。 怎么了?

#[cfg(windows)]
extern crate winapi;

use winapi::ctypes::c_void;

use winapi::um::winuser::{SystemParametersInfoA, SPIF_UPDATEINIFILE, SPI_SETDESKWALLPAPER};

fn main() {
    let mut image_path = "Path to Image";
    let image_path_c_ptr: *mut c_void = &mut image_path as *mut _ as *mut c_void;

    unsafe {
        SystemParametersInfoA(
            SPI_SETDESKWALLPAPER,
            0,
            image_path_c_ptr,
            SPIF_UPDATEINIFILE,
        );
    }
}

【问题讨论】:

  • 不是你的问题,但已经有一个可以设置壁纸的板条箱:github.com/reujab/wallpaper.rs
  • 嘿,谢谢,我会看看这个,因为我仍然需要弄清楚如何为不同的显示器设置壁纸编辑:啊该死的板条箱也只支持一个显示器......

标签: winapi rust wallpaper


【解决方案1】:

Rust 字符串不是 C 字符串。您应该改用 CString 与 C 代码交互:

use std::ffi::CString;

// use ...

fn main() {
    let mut image_path = CString::new("Path to Image").unwrap();

    unsafe {
        SystemParametersInfoA(
            SPI_SETDESKWALLPAPER,
            0,
            image_path.as_ptr() as *mut c_void,
            SPIF_UPDATEINIFILE,
        );
    }
}

详细说明:image_path&str(胖指针)。通过对其进行可变引用,您将获得&mut &str。然后将它传递给 C,C 将取消引用指针并获得 &str

但是 C 代码不知道如何处理 Rust 类型:它只知道 C 字符串,而是期望指向第一个字节的指针。它还期望字符串以NUL 终止,而Rust 字符串不是。因此,在这种情况下,将 Rust &str 传递给 C 代码是没有意义的,而这正是 CStrCString 存在的原因。

【讨论】:

  • 嘿,谢谢。现在可以了。不过,您的 CString 类型有点错误,我在问题中添加了工作代码。
  • 另一个问题,你有没有机会知道我是否可以使用 SystemParametersInfo 单独设置不同屏幕的背景?
  • 对不起,我还没有真正使用过 WINAPI,所以我不能评论它的细节。至于类型,我认为CStr 应该可以工作,因为你有一个静态字符串,不是吗?
  • 编译器在使用您的代码时抱怨。我查阅了 CStr Docs,示例使用 CString::new()
  • 哦,你说的是&mut &str而不是&str,仍然可以使用UB &str,但没关系
【解决方案2】:

这是我最后的工作代码:

#[cfg(windows)]
extern crate winapi;

use std::ffi::CString;
use winapi::ctypes::c_void;

use winapi::um::winuser::{SystemParametersInfoA, SPIF_UPDATEINIFILE, SPI_SETDESKWALLPAPER};

fn main() {
    let mut image_path = CString::new("Path to Image").unwrap();

    unsafe {
        SystemParametersInfoA(
            SPI_SETDESKWALLPAPER,
            0,
            image_path.as_ptr() as *mut c_void,
            SPIF_UPDATEINIFILE,
        );
    }
}

【讨论】:

    猜你喜欢
    • 2016-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多