gpt4 book ai didi

linker - Rust 无法将绑定(bind)链接到 C 库

转载 作者:行者123 更新时间:2023-11-29 08:14:20 25 4
gpt4 key购买 nike

我按照 rust-bindgen 教程为 the scrypt C library 做了绑定(bind)。由于链接错误,我无法运行测试:

/home/user/project/rust-scrypt/src/lib.rs:32: undefined reference to `crypto_scrypt'
collect2: error: ld returned 1 exit status

和我的测试:

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");
}

绑定(bind)已生成并存在于 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!");
}

还有我的 Cargo.toml

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

[build-dependencies]
bindgen = "0.23"

最佳答案

请重新认识the "Building some native code" case study .具体来说,您已经告知 Rust 库的接口(interface) 是什么,但是您还没有告诉编译器代码在哪里。这就是您遇到的错误:“我找不到 crypto_scrypt 的实现”

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

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

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

请,请,阅读关于 *-sys packages 的部分其中记录了此类集成的最佳实践。即,您的 Cargo.toml 缺少 links key ,如果有人多次尝试链接到这个库中,这将导致问题。

--

注意已经有 crates that purport to provide scrypt .

关于linker - Rust 无法将绑定(bind)链接到 C 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44585573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com