Rust使用Rust For Windows调用CreateProcessA

.toml

[dependencies.windows] 
version = "0.51" 
features = [
    "Win32_Foundation",
    "Win32_Security",
    "Win32_System_Threading",
    "Win32_System_Diagnostics_Debug",
    "Win32_System_Kernel",
    "Win32_System_Memory"
]

[dependencies.encoding_rs]
version = "0.8.33"

main.rs

use encoding_rs::GB18030;
use std::ffi::CString;
use windows::core::{PCSTR, PSTR};
use windows::Win32::System::Threading::{
    CreateProcessA, CREATE_NEW_CONSOLE, PROCESS_INFORMATION, STARTUPINFOA,
};

fn my_create_prcoess(game_path: &str) {
    //初始化结构体
    let mut _process_info = PROCESS_INFORMATION::default();
    let mut _startup_info = STARTUPINFOA::default();
    _startup_info.cb = std::mem::size_of::<STARTUPINFOA>() as u32;

    //拼接命令行
    let game_path_f = format!("{}\\{}", game_path, "text.exe");
    println!("gamepath={}\n game_path_f={}", game_path, game_path_f);

    let commandline = convert_to_pcstr(&game_path_f).expect("Failed to convert string to GBK");
    let currentdirectory = convert_to_pcstr(game_path).expect("Failed to convert string to GBK");
    let success = unsafe {
        CreateProcessA(
            PCSTR::null(),
            PSTR(commandline.as_ptr() as *mut u8),
            None,
            None,
            false,
            CREATE_NEW_CONSOLE,
            None,
            PCSTR(currentdirectory.as_ptr() as *const u8),
            &mut _startup_info,
            &mut _process_info,
        )
    }
    .expect("CreateProcessA failed");
    println!("CreateProcessA 返回值: {:?} {:?}", success, _process_info);



}

//Utf8转GBK
fn convert_to_pcstr(input: &str) -> Result<CString, std::io::Error> {
    let (converted, _, had_errors) = GB18030.encode(input);
    if had_errors {
        Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            "Conversion to ANSI failed",
        ))
    } else {
        Ok(CString::new(converted).unwrap())
    }
}

fn main() {
    my_create_prcoess("e:\\资源\\");
}

你可能感兴趣的:(rust,windows,开发语言)