两次调用 JNI_CreateJavaVM 函数

2022-01-25 00:00:00 c c++ java java-native-interface

我正在使用一个在库代码中调用 JNI_CreateJavaVM 函数的库.但是,我还需要一些 JNI Wrappings 并且我需要调用相同的函数 JNI_CreateJavaVM 以将 JNIEnv* 获取到我的应用程序.

I'm using a library that calls the JNI_CreateJavaVM function inside the library code. However, I also need some JNI Wrappings and I need to call the same function JNI_CreateJavaVM to get the JNIEnv* to my application.

但是第二次调用失败了.

But the second call is failing.

有什么办法吗?

该库不支持获取或设置在该库中创建的JNIEnv*.

The library does not support getting or setting the JNIEnv* created inside the library.

推荐答案

你不能从同一个进程创建多个 JVM:

You cannot create more than one JVM from the same process:

从 JDK/JRE 1.2 开始,不支持在单个进程中创建多个 VM.

As of JDK/JRE 1.2 , creation of multiple VMs in a single process is not supported.

您可以使用 AttachCurrentThread 函数将当前线程附加到现有的 JVM.请参阅Invocation API 的文档.Java 15 中的等效文档 简单地说:

You may be able to attach your current thread to the existing JVM though using AttachCurrentThread function. See the docs for the Invocation API. The equivalent document in Java 15 simply states:

不支持在单个进程中创建多个 VM.

Creation of multiple VMs in a single process is not supported.

您需要一个指向 JavaVM 对象的指针.看看 JNI_GetCreatedJavaVMs() 是否可以帮助你,我不确定这是每个进程(在这种情况下它只会是单个元素列表)还是每台机器.在任何一种情况下,JavaVM 都必须是库正在使用的那个,否则你可能不会做你想做的事.如果您可以访问它,那么您应该能够对 Java 应用程序中的其他对象进行调用,但要确保它是线程安全的.

You will need a pointer to the JavaVM object. See if JNI_GetCreatedJavaVMs() can help you, I'm not sure if this is per-process (in which case it will only ever be a single element list) or per machine. In either case the JavaVM will have to be the one that the library is using or you probably will not be doing what you want. If you can access that then you should be able to make invocations on other objects in your Java application, but make sure that it is thread-safe.

相关文章