在C中,直接使用JNI加载虚拟机,也是很有意思的想法。
这个工作不难,吾已经完成了。下面这个代码不是我的代码,没有真正测试过。以后有机会再测试。
#include <jni.h> using namespace std; int main(const int argc, const char** argv) { JavaVMOption options[7]; JNIEnv *env; JavaVM *jvm; JavaVMInitArgs vm_args; options[0].optionString = "-XX:+UseG1GC"; options[1].optionString = "-XX:-UseAdaptiveSizePolicy"; options[2].optionString = "-XX:-OmitStackTraceInFastThrow"; options[3].optionString = "-Xmn512m"; options[4].optionString = "-Xmx2048m"; options[5].optionString = "-Djava.library.path=natives"; options[6].optionString = "-Djava.class.path=.;libraries.zip;main.jar"; std::memset(&vm_args, 0, sizeof(vm_args)); vm_args.version = JNI_VERSION_1_8; vm_args.nOptions = 7; vm_args.options = options; cout << "start creat jvm!\n"; long status = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args); if (status == JNI_ERR) { return 0; } cout << "jvm created success\n"; jclass cls = env->FindClass("main/Main"); if (cls != NULL) { jmethodID mid = env->GetStaticMethodID(cls, "main", "([Ljava/lang/String;)V"); if (mid != NULL) { jclass clz_string = env->FindClass("java/lang/String"); jobjectArray result = env->NewObjectArray(2, clz_string, NULL); jstring arg0 = env->NewStringUTF("first"); env->SetObjectArrayElement(result, 0, arg0); jstring arg1 = env->NewStringUTF("second"); env->SetObjectArrayElement(result, 1, arg1); env->CallStaticVoidMethod(cls, mid, result); } else { cout << "class not found\n"; } jvm->DestroyJavaVM(); return 0; }