Invoke jar from C++ using JNI

41 Views Asked by At

I am trying to call a .jar file from native code. It seems no matter what I try, I always get the following error:

Error occurred during initialization of VM
Failed setting boot class path.

I have already tried several jars to see if it was some problem with the application itself, and I have tried to unpack the jar and load the main class directly, but nothing seems to work. I am using the JDK 21 with a jar that has been validated to work.

The code is below:

#include <jni.h>
#include <iostream>
#include <string>

class JavaVMExecutor {
private:
    JavaVM* jvm;
    JNIEnv* env;
    jclass mainClass;
    jmethodID mainMethod;

public:
    JavaVMExecutor(const std::string& classpath) {
        JavaVMInitArgs vm_args;
        JavaVMOption options[1];
        std::string classPathOption = "-Djava.class.path=" + classpath;
        options[0].optionString = const_cast<char*>(classPathOption.c_str());

        vm_args.version = JNI_VERSION_1_8;
        vm_args.nOptions = 1;
        vm_args.options = options;
        vm_args.ignoreUnrecognized = JNI_FALSE;

        // !!! THIS IS WHERE THE ERROR OCCURS !!!
        JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
        mainClass = env->FindClass("MainClassName");
        mainMethod = env->GetStaticMethodID(mainClass, "main", "([Ljava/lang/String;)V");
    }

    void invoke() {
        jstring arg = env->NewStringUTF("");
        jobjectArray args = env->NewObjectArray(1, env->FindClass("java/lang/String"), arg);
        env->CallStaticVoidMethod(mainClass, mainMethod, args);
        env->DeleteLocalRef(arg);
        env->DeleteLocalRef(args);
    }

    void kill() {
        jvm->DestroyJavaVM();
    }

    ~JavaVMExecutor() {
        kill();
    }
};

int main() {
    JavaVMExecutor executor("C:\\Users\\InfiniPLEX\\Desktop\\Newfolder\\mcaselector-2.3\\net\\querz\\mcaselector\\Main.class");
    executor.invoke();
    return 0;
}

0

There are 0 best solutions below