【问题标题】:Link Error during Rust compilation (Cargo)Rust 编译期间的链接错误(Cargo)
【发布时间】:2020-01-15 12:09:04
【问题描述】:

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

我的代码一直在工作,直到我做了一点变量更改,编译给了我一个错误:

= 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时不会发生错误。

【问题讨论】:

  • 如果将#[no_mangle] 属性添加到函数定义(在extern "system" 块中),错误会消失吗?编码错误似乎不是由于链接器本身,而是由于 Cargo 不了解您的语言环境。
  • 不,没有用。
  • 我还尝试仅使用 rustc 并通过使用 Rust std 中的类型将 libc 从货物中留下,但我仍然遇到相同的错误。我真的很困惑。

标签: winapi rust linker ffi rust-cargo


【解决方案1】:

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

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

您还需要安装 Windows 10 SDK。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-30
    • 1970-01-01
    • 2022-12-23
    • 2020-12-23
    • 2022-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多