Link Rust 编译期间出错(Cargo)

Link Error during Rust compilation (Cargo)

我正在使用 Rust FFI 调用一些 WinAPI 函数(在本例中为 MessageBoxA)。

我的代码一直有效,直到我做了一点变量更改并且编译给了我一个错误:

= note: Non-UTF-8 output: WinAPI-dd8845a539e186b8.4ojwfrbxjnkzuhga.rcgu.o : er
ror LNK2019: symbole externe non r\xe9solu MessageBoxA r\xe9f\xe9renc\xe9 dans l
a fonction _ZN6WinAPI4main17hdf93991da0bc3966E\r\nd:\core\Confidential\Forens
ic\Rust\WinAPI\target\debug\deps\WinAPI-dd8845a539e186b8.exe : fatal error
 LNK1120: 1 externes non r\xe9solus\r\n

最后一行是法语,意思是LNK1120: 1 unresolved external

我知道这是一个编码错误,但我不知道如何解决它。

所以我取消了我在代码中所做的小改动,但它一直显示那个奇怪的消息(错误消息实际上更大但无法理解)。

实际上是一个cargo项目,如果要查看代码:

#[cfg(windows)]
#[link(name = "user32", kind = "dylib")]
extern crate libc;
mod ffi{
    use libc::{c_uint,uintptr_t,c_void};
    type HANDLE = *mut c_void;
    pub type UINT = c_uint;
    pub type UINT_PTR = uintptr_t;
    pub type HWND = HANDLE;
    pub type LPCTSTR = *const i8;
    pub const MB_OK: u32 = 0x0;
    pub const MB_OKCANCEL: u32 = 0x00000001;
    pub const MB_ICONWARNING: u32 = 0x00000030;
    pub const MB_ICONINFORMATION: u32 = 0x00000040;
    pub const MB_ICONQUESTION: u32 = 0x00000020;
}
extern "system"{
    fn MessageBoxA(hWnd: ffi::HWND, lpText: ffi::LPCTSTR, lpCaption: ffi::LPCTSTR, uType: u32) -> u32;
}
use ffi::LPCTSTR;
use ffi::MB_OK;
use ffi::MB_ICONINFORMATION;
fn main() -> std::io::Result<()>{
    unsafe{
        let buffer: &[u8] = &[97,99,107,101,0]; // "acke" as a null terminated str
        let lpData: LPCTSTR = core::str::from_utf8_unchecked(buffer).as_ptr() as *const i8;
        let lpCaption: LPCTSTR = "Information".as_ptr() as *const i8;
        MessageBoxA(
            std::ptr::null_mut(),
            lpData,
            lpCaption,
            MB_OK | MB_ICONINFORMATION,
        );
    };
    return Ok(());
}
#[cfg(not(windows))]
fn main() -> std::io::Result<()>{
    println!("That program only runs on Windows 10 architectures.");
    return Ok(());
}

重要提示: 当我在评论中调用 MessageBoxA 时,错误没有发生。

由于 link.exe 的编码问题,我将 Visual Studio 默认语言更改为英语。

然后我收到关于 unresolved external: MessageBoxA@16 的错误。为了解决这个问题,我在 #[link(name="user32")] 声明之后直接移动了行 extern "system"{ /* Functions prototypes */ }

您还需要安装Windows 10 SDK。

感谢 rustup.exe 提供了非常好的安装指示!