rustjava-native-interfaceffidll-injectionjnienv

How do I get a JavaVM or JNIEnv from an already-running JVM using JNI?


I am working on a project which involves Rust and Java. I need to be able to use the JNI from the Rust side, without the Java side calling invoking it (because it is not my code). So far, I have been able to ensure my DLL is injected (open a small window on keypress, I have been using this for debugging).

A shortened example of the relevant code is the following:

use jni::sys::{JNI_GetCreatedJavaVMs, JNIInvokeInterface_};


let jvm_ptr = null_mut() as *mut *mut *const JNIInvokeInterface_;
let count = null_mut();

// hasn't crashed

JNI_GetCreatedJavaVMs(jvm_ptr, 1, count);  // https://docs.rs/jni/latest/jni/sys/fn.JNI_GetCreatedJavaVMs.html

// crashes

My question is this: is it possible to/how do I get a JNI environment in this situation?


Solution

  • With the help of the comments, I got that crash to stop happening. The trick was to pre-allocate an array.

    let jvm_ptr = Vec::with_capacity(1);
    let count = null_mut();
    
    JNI_GetCreatedJavaVMs(jvm_ptr.as_mut_ptr(), 1, count);