用Invocation API在C/C++代码中访问Java代码
测试用例由两部分组成,InvocationApiTest.java 和invocationApi.c,在c代码中访问Java代码的main函数。
编写Java代码:
点击(此处)折叠或打开
-
public class InvocationApiTest
-
{
-
public static void main(String[] args)
-
{
-
System.out.println(args[0]);
-
}
-
}
编译
InvocationApiTest.java:
javac InvocationApiTest.java
编写c程序代码invocationApi.c:
-
#include <jni.h>
-
#include <stdio.h>
-
-
int main()
-
{
-
JNIEnv *env;
-
JavaVM *vm;
-
JavaVMInitArgs vm_args;
-
JavaVMOption options[1];
-
jint res;
-
jclass cls;
-
jmethodID mid;
-
jstring jstr;
-
jclass stringClass;
-
jobjectArray args;
-
-
//1、生成Java虚拟机选项
-
options[0].optionString = "-Djava.class.path=.";
-
vm_args.version = 0x00010002;//JNI_VERSION_1_6;//
-
vm_args.options = options;
-
vm_args.nOptions = 1;
-
vm_args.ignoreUnrecognized = JNI_TRUE;
-
-
//2、生成Java虚拟机
-
res = JNI_CreateJavaVM(&vm, (void**)&env, &vm_args);
-
if (res < 0) {
-
-
fprintf(stderr, "Can't create Java VM\n");
-
-
exit(1);
-
-
}
-
//3、查找并加载类
-
cls = (*env)->FindClass(env, "InvocationApiTest");
-
-
//4、获取main()方法的ID
-
mid = (*env)->GetStaticMethodID(env, cls, "main", "([Ljava/lang/String;)V");
-
-
//5、生成字符串对象,用作main()方法的参量
-
jstr = (*env)->NewStringUTF(env, "Hello Invocation API!!");
-
stringClass = (*env)->FindClass(env, "java/lang/String");
-
args = (*env)->NewObjectArray(env, 1, stringClass, jstr);
-
-
//6、调用main()方法
-
(*env)->CallStaticVoidMethod(env, cls, mid, args);
-
-
//7、销毁Java虚拟机
-
(*vm)->DestroyJavaVM(vm);
-
-
return 0;
-
}
编译c程序:
cl -I "D:\Program Files\Java\jdk1.8.0_25\include" -I "D:\Program Files\Java\jdk1.8.0_25\include\win32" InvocationApi.c -link "D:\Program Files\Java\jdk1.8.0_25\lib\jvm.lib"
执行
invocationApi.exe输出:
Hello Invocation API!!
注意事项:
最后还需要在环境变量PATH中添加jvm.dll动态链接库的路径%JAVA_HOME%jre\bin\client,不然的话创建Java虚拟机会失败。
还可以把生成的i
nvocationApi.exe和InvocationApiTest.class拷贝到jvm.dll所在的目录中,这样也可以执行。
阅读(1616) | 评论(0) | 转发(0) |