Java – store the JNI Java Env variable

javajava-native-interface

I'm making a lib so that cpp apps can communicate with the JVM. Suppose that the JVM has already started how can I make a cpp binary communicate with the JVM? I think the best solution is to store the JNI env variable in the shared object (so) so I can include it on the cpp and use later.

Is that possible?

EDIT —-

I want to get the JavaVM Interface outside of the JVM, something like this method:

  • GetJavaVM returns the JavaVM interface pointer for the current virtual machine instance.

Best Answer

Your question is unclear: it sounds like you want a C++ application to communicate with a JVM running as a separate process. In which case you need to use some form of inter-process communication such as pipes, sockets, CORBA, whatever. The JNIEnv pointer, like all pointers, is only valid within the process in which it's used.

The only case that I think fits your question is if you start a Java program, call into a native method, then that native method starts up separate threads. In which case, no, you can't share the JNIEnv pointer, because it's tied to a thread. However, you can use the JNI invocation API to access the Java VM from your C++ thread.