gpt4 book ai didi

c++ - 动态加载 jvm.dll 而不链接它

转载 作者:行者123 更新时间:2023-12-03 06:53:43 25 4
gpt4 key购买 nike

所以,最近我一直在考虑通过 C/C++ 调用 Java 方法,但随之而来的一个大问题是必须将 jvm.dll 添加到路径中,我一直在想,如果我找到了,这是否可行jvm.dll 通过获取 JAVA_HOME 并在 Linux/MacOS 的情况下放置“\bin\server”或“/bin/server”,然后我会找到它,例如在 Windows 上使用 Windows.h 中的 LoadLibrary 加载函数和让它在不链接任何东西的情况下工作?我可以考虑这种可能性,但我一直无法找到我需要的工具,例如我应该加载哪个方法,它有什么参数,它返回什么?等等

最佳答案

你只需要使用 JNI_CreateJavaVM 来创建一个 JVM,你通常会从那里得到一个函数指针结构,所以你只需要使用 dlsym 来做一些功能。我使用了 dl* 函数,但它在 Windows 上与 LoadLibraryGetProcAddress 完全相同。

#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++ - 动态加载 jvm.dll 而不链接它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63858264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com