So, lately I've been thinking about calling Java Methods through C/C++ but a great issue that comes is having to add jvm.dll to the path, I've been thinking wouldn't it be possible if I found the jvm.dll by getting JAVA_HOME and putting "\bin\server" or "/bin/server" in case of Linux/MacOS, then I would find it and for example on windows use LoadLibrary from Windows.h to load the function and make it work without linking anything? I can think about the possibility but I haven't been able to find the tools I need, for example which method should I load, what arguments does it have, what does it return? etc
You would just have to use JNI_CreateJavaVM to create a JVM and from there, you get often a structure of function pointers, so you only have to use dlsym for some functions.
I used the dl* functions, but it's quite the same on windows with LoadLibrary and 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With