microsoft / windows-rs

Rust for Windows
https://kennykerr.ca/rust-getting-started/
Apache License 2.0
10.1k stars 473 forks source link

Simpler PCWSTR from Rust str #3105

Closed JMS55 closed 2 weeks ago

JMS55 commented 2 weeks ago

Suggestion

Currently I'm using PCWSTR::from_raw(HSTRING::from(settings.entry_point).as_ptr())

kennykerr commented 2 weeks ago

This is intentionally verbose since you're dealing with a dangling pointer. You should carefully track the lifetime of the HSTRING in this case:

use windows::core::*;

fn main() {
    unsafe {
        let s = "Hello";

        let h = HSTRING::from(s);
        let w = PCWSTR(h.as_ptr());

        println!("{}", w.display());
    }
}
JMS55 commented 2 weeks ago

Thanks for pointing out the dangling pointer. Just to confirm, HSTRING is like Rust String, and PCWSTR is like Rust &str, ownership wise?

kennykerr commented 1 week ago

Almost. HSTRING is an owned strings like the Rust Standard Library's String.

But PCWSTR is just a pointer without ownership or lifetime. This is unlike &str which does include lifetime tracking. This is why no implicit or trait-based conversions are provided for PCWSTR and friends - there's no lifetime to ensure that it will be safe.