动态加载 jvm.dll 而不链接它
Dynamically load jvm.dll without linking it
所以,最近我一直在考虑通过 C/C++ 调用 Java 方法,但是随之而来的一个大问题是必须将 jvm.dll 添加到路径中,我'我一直在想,如果我通过获取 JAVA_HOME 并在 Linux/MacOS 的情况下放置“\bin\server”或“/bin/server”来找到 jvm.dll 是不是可能的,然后我会找到它,例如在 windows 上使用 Windows.h 中的 LoadLibrary 加载函数并使其在不链接任何东西的情况下工作?我可以考虑这种可能性,但我一直无法找到我需要的工具,例如我应该加载哪个方法,它有什么参数,它是什么return?等等
您只需要使用 JNI_CreateJavaVM
来创建一个 JVM,并且从那里,您通常会得到一个函数指针结构,因此您只需要对某些函数使用 dlsym
。
我使用了 dl*
函数,但在 windows 上与 LoadLibrary
和 GetProcAddress
.
完全相同
#include <jni.h> //For the typedefs, struct definitions,...
....
typedef jint (*createJVMFuncPointer_t)(JavaVM **p_vm, void **p_env, void *vm_arg);
....
//I ommitted all checks for errors.
void* handleToLibJVM=dlopen(yourPathToJvmDllOrSo,RTLD_LAZY);
createJVMFuncPointer_t createJVM=(createJVMFuncPointer_t)dlsym(handleToLibJVM,"JNI_CreateJavaVM");
JavaVM *jvm;
JNIEnv *env;
JavaVMOption* options = ...;
//TODO: Initialize options (For things like the classpath and other options)
jint errorCode=createJVM(&jvm, (void**)&env, &vm_args);
//From here you can start looking for your methods written in Java.
jclass cls=(*env)->FindClass(env,"foo/bar/SomeClass");
//Search for method in this class with name baz, taking two ints and returning void.
jmethodID mid=(*env)->GetStaticMethodID(env,cls,"baz","(II)V");
(*env)->CallStaticVoidMethod(env,cls,mid,1,2);
//TODO: Cleanup`(dlclose, free, DestroyJavaVM)
所以,最近我一直在考虑通过 C/C++ 调用 Java 方法,但是随之而来的一个大问题是必须将 jvm.dll 添加到路径中,我'我一直在想,如果我通过获取 JAVA_HOME 并在 Linux/MacOS 的情况下放置“\bin\server”或“/bin/server”来找到 jvm.dll 是不是可能的,然后我会找到它,例如在 windows 上使用 Windows.h 中的 LoadLibrary 加载函数并使其在不链接任何东西的情况下工作?我可以考虑这种可能性,但我一直无法找到我需要的工具,例如我应该加载哪个方法,它有什么参数,它是什么return?等等
您只需要使用 JNI_CreateJavaVM
来创建一个 JVM,并且从那里,您通常会得到一个函数指针结构,因此您只需要对某些函数使用 dlsym
。
我使用了 dl*
函数,但在 windows 上与 LoadLibrary
和 GetProcAddress
.
#include <jni.h> //For the typedefs, struct definitions,...
....
typedef jint (*createJVMFuncPointer_t)(JavaVM **p_vm, void **p_env, void *vm_arg);
....
//I ommitted all checks for errors.
void* handleToLibJVM=dlopen(yourPathToJvmDllOrSo,RTLD_LAZY);
createJVMFuncPointer_t createJVM=(createJVMFuncPointer_t)dlsym(handleToLibJVM,"JNI_CreateJavaVM");
JavaVM *jvm;
JNIEnv *env;
JavaVMOption* options = ...;
//TODO: Initialize options (For things like the classpath and other options)
jint errorCode=createJVM(&jvm, (void**)&env, &vm_args);
//From here you can start looking for your methods written in Java.
jclass cls=(*env)->FindClass(env,"foo/bar/SomeClass");
//Search for method in this class with name baz, taking two ints and returning void.
jmethodID mid=(*env)->GetStaticMethodID(env,cls,"baz","(II)V");
(*env)->CallStaticVoidMethod(env,cls,mid,1,2);
//TODO: Cleanup`(dlclose, free, DestroyJavaVM)