winapi - Rust 编译期间的链接错误(Cargo)

标签 winapi rust linker ffi rust-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 提供了非常好的安装指示!

关于winapi - Rust 编译期间的链接错误(Cargo),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57926615/

相关文章:

c - 在 WINAPI 中指定窗口绘画区域

iterator - Rhs 在有关 PartialEq 的编译器错误消息中指的是什么?

visual-studio - 这个错误信息是什么意思: LINK : fatal error LNK1104: cannot open file 'TEMPFILE'

c - VLC3编译错误: linking issue with the libavutil library

visual-studio-2010 - 在带有openCV的Visual Studios 2010中构建项目时无法解析的外部符号

c - 在C编程中使用窗口类型图形

c++ - 使用 GDI 将文本旋转 90 度

c# 移动 Winamp 主窗口

Rust GTK+ 示例无法编译,因为 Option<&str> : From<Option<&String>> is not satisfied

rust - 什么时候应该使用函数指针而不是闭包?