用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所在的目录中,这样也可以执行。
阅读(1424) | 评论(0) | 转发(0) |