获取当前进程中的JavaVM *的所有实例? [英] Get all instance of JavaVM* in the current process?
问题描述
这仅适用于Windows.
JNI是否提供任何API来返回调用进程JavaVM*
的所有实例?
考虑以下情形,将C ++ dll注入到java.exe
进程中.现在的问题是,C ++ dll如何在运行它的进程中找到JavaVM*
的当前实例?
This is only specific to Windows.
Does JNI provide any API that returns all instance of JavaVM*
of the calling process?
Consider the following scenario, a C++ dll is injected into a java.exe
process. Now the question is, how can the C++ dll locate the current instance of JavaVM*
within the process it's running from?
据我所知,所有JNI调用API都需要一个JNIEnv
对象,该对象只能从JavaVM*
获取,对吗? http://docs.oracle.com/javase /1.5.0/docs/guide/jni/spec/functions.html
As far as I know, all JNI invocation API require a JNIEnv
object which can only be acquired from JavaVM*
right? http://docs.oracle.com/javase/1.5.0/docs/guide/jni/spec/functions.html
获取JavaVM*
的传统方法是通过JNI_OnLoad
,但是由于我没有编写Java可以使用的本机库,因此我认为这不会奏效. http://docs.oracle.com/javase /1.5.0/docs/guide/jni/spec/invocation.html
The traditional way of getting JavaVM*
is via JNI_OnLoad
but since I'm not writing a native library to be consumed by Java, I don't think that would do the trick. http://docs.oracle.com/javase/1.5.0/docs/guide/jni/spec/invocation.html
推荐答案
You can use JNI_GetCreatedJavaVMs
:
jsize nVMs;
JNI_GetCreatedJavaVMs(NULL, 0, &nVMs); // 1. just get the required array length
JavaVM** buffer = new JavaVM*[nVMs];
JNI_GetCreatedJavaVMs(buffer, nVMs, &nVMs); // 2. get the data
此代码是安全"版本,它询问缓冲区必须有多大,然后再次调用以获取数据.但是,主要的Windows JVM(热点)每个进程不支持多个JVM,因此仅为一个元素分配一个缓冲区就足够了. JNI_GetCreatedJavaVMs
是调用API的一部分,因此由jvm.dll
导出.
This code is the "safe" version that asks how big the buffer has to be and then calls a second time to get the data. However, the major Windows JVM (Hotspot) doesn't support more than one JVM per process, so it may be sufficient for you to just allocate a buffer for one element. JNI_GetCreatedJavaVMs
is a part of the invocation API and therefore exported by the jvm.dll
.
我不是在编写要由Java使用的本机库
I'm not writing a native library to be consumed by Java
如果要在库中创建JVM,这就是您所需要的,因为无论如何都必须加载jvm.dll
.我真的不能为您提供太多帮助,因为您没有写出将如何准确调用您的库.如果您的库被另一个创建JVM或从JVM加载的本机库使用,并且无论出于何种原因都没有将JavaVM*
传递给您,则可以尝试以下方法:
If you are creating the JVM in your library, that's all you need because you have to load the jvm.dll
anyways. I can't really help you much because you're not writing how exactly your library is going to be invoked. If your library is used by another native library that either creates the JVM or is loaded from the JVM and it doesn't pass the JavaVM*
to you for whatever reason, you could try something like this:
#include <Windows.h>
#include <jni.h>
// ...
typedef jint (JNICALL * GetCreatedJavaVMs)(JavaVM**, jsize, jsize*);
GetCreatedJavaVMs jni_GetCreatedJavaVMs;
// ...
jni_GetCreatedJavaVMs = (GetCreatedJavaVMs)GetProcAddress(GetModuleHandle(
TEXT("jvm.dll")), "JNI_GetCreatedJavaVMs");
这篇关于获取当前进程中的JavaVM *的所有实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!