簡體   English   中英

從Rust調用時,Java JNI在退出時崩潰

[英]Java JNI crashes on exit when called from Rust

我想啟動一個JVM並從Rust調用一個靜態Java方法。 最初,一切正常,我在控制台中看到了預期的輸出。 但是,在Java方法結束之前,我遇到了分段錯誤。

這是輸出:

Hello World!
Segmentation fault (core dumped)

這是Java類(打包在一個胖的Jar中):

public class HelloWorld {
    public static void greetings() {
        System.out.println("Hello World!");
    }
}

這是我執行的Rust代碼:

extern crate rucaja;

use rucaja::{Jvm, jvalue};

fn main() {

    // The class path must contain the fat JAR.
    let class_path = "-Djava.class.path=./java/target/hello-0.1.0.jar";

    let jvm_options = [class_path];

    unsafe {
        // Instantiate the embedded JVM.
        let jvm = Jvm::new(&jvm_options);

        // Resolve the Java wrapper class from the fat JAR.
        let main_class = jvm.get_class("HelloWorld").expect("Could not find Java class");

        // Resolve Java methods in that wrapper class.
        let greetings_method = jvm.get_static_method(
            &main_class,
            "greetings",
            "()V"
        ).expect("Could not find Java method");

        // Prepare (no) arguments
        let args: Vec<jvalue> = vec![
        ];

        // Call the method
        jvm.call_static_object_method(
            &main_class,
            &greetings_method,
            args.as_ptr()
        );
    }

    println!("Done");
}

我嘗試使用gdb運行它,但是堆棧看起來壞了:

Program received signal SIGSEGV, Segmentation fault.
0x00007fffe575d2b4 in ?? ()
(gdb) bt
#0  0x00007fffe575d2b4 in ?? ()
#1  0x0000000000000246 in ?? ()
#2  0x00007fffe575d160 in ?? ()
#3  0x00007fffffffd530 in ?? ()
#4  0x00007fffffffd4e0 in ?? ()
#5  0x00007ffff790a6ad in ?? () from /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/amd64/server/libjvm.so
Backtrace stopped: previous frame inner to this frame (corrupt stack?)

您認為細分錯誤的原因是什么?

Java方法不返回一個對象,所以jvm.call_static_void_method(...)必須被用來代替jvm.call_static_object_method(...)

正確的代碼:

// Call the method
jvm.call_static_void_method(
    &main_class,
    &greetings_method,
    args.as_ptr()
);

然后程序運行正常:

Hello World!
Done

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM