如何在不引起编译错误的情况下从jni crate导入JavaVM?

时间:2019-06-30 13:26:12

标签: rust

我正在尝试模拟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。

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

1 个答案:

答案 0 :(得分:0)

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

最重要的是对Cargo.toml的修改。对于不熟悉Cargo.toml编写经验的人们,包括此子句可能会为jni crate的文档字符串带来好处:

[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"]}