【问题标题】:How can I import JavaVM from the jni crate without causing compile errors?如何从 jni crate 导入 JavaVM 而不会导致编译错误?
【发布时间】:2019-07-22 21:51:36
【问题描述】:

我正在尝试模拟 https://github.com/jni-rs/jni-rs/blob/master/tests/jni_api.rshttps://github.com/jni-rs/jni-rs/blob/master/tests/util/mod.rs 的测试用例。我用 main.rs 创建了一个项目

use jni::{InitArgsBuilder, JNIVersion, JavaVM};

fn main() {
    let jvm_args = InitArgsBuilder::new()
        .version(JNIVersion::V8)
        .option("-Xcheck:jni")
        //.option(format!("-Djava.class.path={}", heinous_classpath()))
        .build()
        .unwrap_or_else(|e| panic!("{}", e.display_chain().to_string()));

    let jvm = JavaVM::new(jvm_args);
}

和 Cargo.toml:

[package]
name = "rust_call_jni"
version = "0.1.0"
authors = ["Robert Forsman <git@thoth.purplefrog.com>"]
edition = "2018"

[dependencies]
jni = "0.12.3"

当我执行cargo build 时,我收到以下错误:

error[E0432]: unresolved import `jni::InitArgsBuilder`
 --> src/main.rs:1:11
  |
1 | use jni::{InitArgsBuilder, JNIVersion, JavaVM};
  |           ^^^^^^^^^^^^^^^ no `InitArgsBuilder` in the root

error[E0599]: no function or associated item named `new` found for type `jni::wrapper::java_vm::vm::JavaVM` in the current scope
  --> src/main.rs:12:23
   |
12 |     let jvm = JavaVM::new(jvm_args);
   |               --------^^^
   |               |
   |               function or associated item not found in `jni::wrapper::java_vm::vm::JavaVM`

我正在使用 Rust 1.34.2。

如何修改我的源代码以正确导入和调用构造函数?

【问题讨论】:

  • 它无法编译,因为它需要#[cfg(feature = "invocation")],但我找不到此功能的含义。很可能它不在稳定频道上。

标签: rust


【解决方案1】:

基于the pointer from Svetlin Zarev,我能够翻阅文档并找出启用调用功能的正确语法。

最重要的是对 Cargo.toml 的修改。对于编写 Cargo.toml 经验较少的人来说,jni 板条箱的文档字符串可能会受益于包含此子句:

[package]
name = "rust_call_jni"
version = "0.1.0"
authors = ["Robert Forsman <git@thoth.purplefrog.com>"]
edition = "2018"

[dependencies.jni]
version = "0.12.3"
features = ["invocation"]

我不得不修改 main.rs 以修复一些被早期错误掩盖的错误:

use jni::{InitArgsBuilder, JNIVersion, JavaVM};

fn main() {
    let jvm_args = InitArgsBuilder::new()
        .version(JNIVersion::V8)
        .option("-Xcheck:jni")
        //.option(&format!("-Djava.class.path={}", heinous_classpath()))
        .build()
        .unwrap_or_else(|e| //panic!("{}", e.display_chain().to_string())
        panic!("{:?}", e));

    let jvm = JavaVM::new(jvm_args);
}

事实证明,我后来发现了另一种 Cargo.toml 语法用于具有多个属性的依赖项:

jni = {version="0.12.3", features=["invocation"]}

【讨论】:

  • 您必须将 LD_LIBRARY_PATH 设置为指向 libjvm 的正确位置,否则它将在运行时失败并显示找不到它的消息。
  • 是的,我在 IntelilJ 运行配置的环境中这样做。
猜你喜欢
  • 2021-01-08
  • 2021-11-10
  • 2015-11-18
  • 1970-01-01
  • 2020-07-05
  • 1970-01-01
  • 1970-01-01
  • 2017-04-04
  • 2011-06-09
相关资源
最近更新 更多