Rust 无法将绑定链接到 C 库

Con*_*ine 3 linker ffi rust

我按照rust-bindgen教程为scrypt C 库进行绑定。由于链接错误,我无法运行测试:

/home/user/project/rust-scrypt/src/lib.rs:32: undefined reference to `crypto_scrypt'
      collect2: error: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

和我的测试:

include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
// ...
// ...
#[test]
fn test_script() {
  let mut kdf_salt = to_bytes("fd4acb81182a2c8fa959d180967b374277f2ccf2f7f401cb08d042cc785464b4");
    let passwd = "1234567890";
    let mut buf = [0u8; 32];

    unsafe {
        crypto_scrypt(passwd.as_ptr(), passwd.len(), kdf_salt.as_mut_ptr(), kdf_salt.len(),
                      2, 8, 1, buf.as_mut_ptr(), 32);
    }

    println!(">> DEBUG: {:?}", buf);
    // "52a5dacfcf80e5111d2c7fbed177113a1b48a882b066a017f2c856086680fac7");
}
Run Code Online (Sandbox Code Playgroud)

绑定已生成并存在于bindings.rs. 我不知道为什么链接器会抛出错误。

这是我的builds.rs

extern crate bindgen;

use std::env;
use std::path::PathBuf;

fn main() {
    let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
    let bindings = bindgen::Builder::default()
        .no_unstable_rust()
        .header("wrapper.h")
        .generate()
        .expect("Unable to generate bindings");

    bindings
        .write_to_file(out_path.join("bindings.rs"))
        .expect("Couldn't write bindings!");
}
Run Code Online (Sandbox Code Playgroud)

还有我的Cargo.toml

[package]
name = "rust-scrypt"
version = "0.0.1"
build = "build.rs"

[build-dependencies]
bindgen = "0.23"
Run Code Online (Sandbox Code Playgroud)

She*_*ter 7

请重新熟悉“构建一些本机代码”案例研究。具体来说,你已经告诉 Rust库的接口是什么,但你还没有告诉编译器代码在哪里。这就是您收到的错误:“我找不到crypto_scrypt”的实现

您需要将库添加到链接器路径并指示它进行链接。

从链接的案例研究中,您的构建脚本可以通知编译器库的位置以及要链接的内容:

println!("cargo:rustc-link-search=native={}", path_to_library);
println!("cargo:rustc-link-lib=static=hello"); // the name of the library
Run Code Online (Sandbox Code Playgroud)

请,请,*-sys阅读有关软件包的部分,其中记录了此类集成的最佳实践。也就是说,您的 Cargo.toml 缺少links key,如果有人尝试多次链接该库,这将导致问题。

--

请注意,已经有一些声称提供 scrypt 的板条箱