从c ++运行jar文件 [英] run jar file from c++
问题描述
我运行下面的c ++代码,ret的值是-1(javavm的创建是falid)
I am runing the follwing c++ code and the value of "ret" is -1 (the create of javavm is falid)
代码的问题是什么?
#include <iostream>
#include <conio.h>
#include <jni.h>
using namespace std;
#pragma comment (lib,"jvm.lib");
int main(){
JavaVM *jvm;
JNIEnv *env;
JavaVMInitArgs vm_args;
JavaVMOption options;
options.optionString="hello.jar";
vm_args.version=JNI_VERSION_1_6;
vm_args.nOptions=1;
vm_args.Option=&options;
vm_args.ignoreUnrecognized=0;
int ret=JNI_CreatJavaVM(&jvm,(void**)&env,&vm_args);
}
这是帮助
推荐答案
如果将 CreateJavaVM
调用中的无效选项传递给 ignoreUnrecognized = 1
它将无法启动JVM。
If you pass in an invalid option to the CreateJavaVM
call, because of the ignoreUnrecognized = 1
it will fail to launch the JVM.
当我使用public static void main方法创建一个简单的jar时,下面的代码,它正确地调用了main方法:
When I create a simple jar with a public static void main method, and use the following code, it correctly invokes the main method:
JavaVM *jvm;
JNIEnv *env;
JavaVMInitArgs vm_args;
JavaVMOption options;
options.optionString = "-Djava.class.path=hello.jar";
vm_args.version = JNI_VERSION_1_6;
vm_args.nOptions = 1;
vm_args.options = &options;
vm_args.ignoreUnrecognized = 0;
int ret = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
if (ret == 0) {
jclass cls = env->FindClass("hello");
if (cls != 0) {
jmethodID meth = env->GetStaticMethodID(cls, "main", "([Ljava/lang/String;)V");
jarray args = env->NewObjectArray(0, env->FindClass("java/lang/String"), 0);
env->CallStaticVoidMethod(cls, meth, args);
}
}
return ret;
这假设 hello.jar
可执行文件的工作目录。如果不是,则需要指定jar文件的完整路径。例如 c:\hello.jar
。
This assumes that hello.jar
is in the working directory of the executable. If it isn't then you need to specify the full path to the jar file. e.g. c:\hello.jar
.
这篇关于从c ++运行jar文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!