将非标准依赖项导入 Rust 库时出现编译错误

问题描述 投票:0回答:1

我目前正在尝试构建一个小型的 Rust 库,可以从 Python 调用(通过

ctypes
的魔力)。我成功地制作了一个“Hello, world!”级别的函数并将其导入到 Python 中,但是当我尝试通过添加素数查找函数来添加另一层复杂性时遇到了困难,该函数利用了
primes
- 外部Rust 标准库。简而言之,如果我运行
cargo build
,那么我会收到以下编译错误:

  --> src/lib.rs:10:5
   |
10 | use primes;
   |     ^^^^^^ no `primes` in the root

Rust 包结构

我的 Rust 包的结构非常简单:

|__src
|    |__lib.rs
|__Cargo.toml

代码

我认为向您展示这个小包中的代码可能会有所帮助。

Cargo.toml

[package]
name = "hosker_primes"
version = "1.0.0"
authors = ["Tom Hosker"]

[lib]
name = "primes_lib"
crate-type = ["dylib"]

[dependencies]
primes = "0.3.0"

src/lib.rs

use std::ffi::CStr;
use std::os::raw::c_char;
use std::os::raw::c_int;
use std::str;

use primes;

fn main() {
    println!("{}", _find_nth_prime(3));
}

fn _find_nth_prime(n: i32) -> i32 {
    let mut count = 0;
    let mut current = 0;

    while count < n {
        current += 1;

        if primes::is_prime(current) {
            count += 1;
        }
    }

    return current as i32;
}

#[no_mangle]
pub extern "C" fn make_contact(c_string_ptr: *const c_char) {
    let bytes = unsafe { CStr::from_ptr(c_string_ptr).to_bytes() };
    let silly_word = str::from_utf8(bytes).unwrap();

    println!("Congratulations! You have made contact with the PRIMES library.");
    println!("This is the silly word you gave me: {}", silly_word);
}

#[no_mangle]
pub extern "C" fn find_nth_prime(c_int_ptr: *const c_int) -> *const c_int {
    let int_ptr = unsafe { c_int_ptr.as_ref().unwrap() };
    let result = _find_nth_prime(*int_ptr) as *const c_int;

    return result;
}
rust dependencies
1个回答
0
投票

但是我找到了解决方案:

  1. 我发现它纯粹是出于运气,而且
  2. 我不知道为什么它会起作用。

看来,如果我将以下行添加到我的

package
Cargo.toml
部分:

edition = "2021"

然后一切就正常了!

这可能是 Cargo 接口的故障吗?如果用户收到缺少字段的警报,而不是进一步出现一些奇怪的导入问题,这不是更有帮助吗?

© www.soinside.com 2019 - 2024. All rights reserved.