从 Rust 调用 C 库会得到"LINK : fatal error LNK1181: cannot open input file"



我正在尝试从Rust调用STM32Cube程序员C库。

这里提供了整个代码以及显示各种尝试的分支:https://github.com/becky112358/rust_c_linking_stm32_cube_programmer

尝试1(在我的GitHub存储库中,分支main(

遵循Rust Bindgen教程:https://rust-lang.github.io/rust-bindgen/

这是我喜欢的方法。一个Rust板条箱包裹着C库。其他Rust板条箱可以包括Rust包装板条箱,而不必担心任何C库。

理论上。

包装C库(libstm32_cube_programmer_sys(的Rust机箱构建正常。它的测试运行正常。Rust机箱调用包装C库(caller(的Rust机箱,但没有构建,而是报告:

= note: LINK : fatal error LNK1181: cannot open input file '.driversCubeProgrammer_API.lib'

为什么caller甚至试图寻找C库?我期望libstm32_cube_programmer_sys处理所有C库到Rust的转换,并且任何当时调用libstm32_cube_programmer_sys的Rust板条箱都可能是纯粹的Rusty(可能有一些不安全(。

  • build.rs中,我最初错误地编写了C库名称,而libstm32_cube_programmer_sys没有构建。更正库名称使libstm32_cube_programmer_sys得以成功生成。所以看起来libstm32_cube_programmer_sys确实打开了C库
  • 我尝试将drivers文件夹的路径添加到我的PATH
  • 我尝试列出C库的绝对路径:
println!("cargo:rustc-link-lib=C:/[blah blah]/drivers/CubeProgrammer_API");

在没有Rust报告的情况下,我找不到如何正确地在路径中馈送:

error: renaming of the library `C` was specified, however this crate contains no `#[link(...)]` attributes referencing this library.



尝试2(分支all_in_one(

main分支中,问题似乎是libstm32_cube_programmer_sys可以找到C库,但caller找不到。因此,我尝试放弃单独的Rust机箱,而使用一个Rust机箱来封装C库并调用C函数。

这次我得到了以下错误,加上一个额外的警告:

= note: caller.59pofysds2mkvvjr.rcgu.o : error LNK2019: unresolved external symbol disconnect referenced in function _ZN6caller4main17ha79648c0a9e86ed0E
.driversCubeProgrammer_API.lib : warning LNK4272: library machine type 'x86' conflicts with target machine type 'x64'



尝试3(分支link_search(

我在互联网上搜索了很多,发现了很多不同的方法来调用Rust的C库。一种方法是使用link-search而不是link-lib。这肯定只会让编译器更加困难,因为你会让它做更多的工作。但我被卡住了,需要尝试不同的东西!

这次我得到以下错误,加上奖金警告:

= note: caller.59pofysds2mkvvjr.rcgu.o : error LNK2019: unresolved external symbol __imp_disconnect referenced in function _ZN6caller4main17ha79648c0a9e86ed0E
.driversCubeProgrammer_API.lib : warning LNK4272: library machine type 'x86' conflicts with target machine type 'x64'



问题

我该如何做到这一点?理想情况下从尝试1,但我会接受任何东西!

当我们有:时

C库<-Rust库<-锈蚀代码

看来

  • 编译时,Rust代码需要能够看到C库,即使它也在调用Rust库
  • 运行时,可能需要将C dll与Rust-exe一起存储

当我发布我最初的问题时,这是我的主要误解。

其他一些提示/提醒:

  • 请确保使用正确的lib文件!(x64、x86等(
  • 也解决警告

最新更新