我想在c++中用jni调用java程序的入口main函数,但是这样创建的jvm比直接用javaw命令运行要卡很多,但是jvm参数设置的都是一样的。在c++中运行,fps只有10-30,直接运行jar却能达到50-100。
求教这是什么原因?有什么改进的办法吗?
#include <jni.h>
using namespace std;
extern "C" {
__declspec(dllexport) DWORD NvOptimusEnablement = 1;
}
int main() {
JavaVMOption options[7];
JNIEnv *env;
JavaVM *jvm;
JavaVMInitArgs vm_args;
long status;
jclass cls;
jmethodID mid;
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";
status = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
if (status != JNI_ERR) {
cout << "jvm created success\n";
cls = env->FindClass("main/Main");
if (cls != 0) {
mid = env->GetStaticMethodID(cls, "main", "([Ljava/lang/String;)V");
if (mid != 0) {
jclass clz_string = env->FindClass("java/lang/String");
if (clz_string != NULL) {
jobjectArray result = env->NewObjectArray(2, clz_string, NULL);
jstring arg0 = env->NewStringUTF("--accessToken");
jstring arg1 = env->NewStringUTF("14233482b8dbad97617757a5c31d5872");
env->SetObjectArrayElement(result, 0, arg0);
env->SetObjectArrayElement(result, 1, arg1);
env->CallStaticVoidMethod(cls, mid, result);
}
}
} else {
cout << "class not found\n";
}
jvm->DestroyJavaVM();
return 0;
} else {
return -1;
}
}
你看过jdk源码中javaw.exe的源码就知道了,它也是用
JNI_CreateJavaVM
实现的,所以可以对比下你的代码跟javaw.exe实现的有什么不同。另外想到两种可能:
Windows下jvm有
server
和client
两种类型,性能差别还是挺大的,javaw.exe
会自动选择(也可以用-server
或-client
指定),用c++调用好像要指定用哪个jvm.dll的;c++编译时用了哪个标准库(单线程还是多线程),不清楚是否会影响到jvm的调用。