一、书写C文件,模拟JDK中自带的java命令
- #include <jni.h>
- #include <stdlib.h>
- #include <stdio.h>
- int main(int argc, char*argv[])
- {
- JavaVM *jvm;
- JNIEnv *env;
- JavaVMInitArgs vm_args;
- JavaVMOption options[1];
- jobjectArray applicationArgs;
- jstring appArg;
- /*
- * Setting VM arguments
- */
- vm_args.version = JNI_VERSION_1_2;
- vm_args.ignoreUnrecognized = JNI_TRUE;
- vm_args.nOptions = 0;
- /*
- * Setting classpath
- */
- char classpath[1024] = "-Djava.class.path=";
- char *env_classpath = getenv("CLASSPATH");
- int mainclass_index = 1;
- if (argc >= 3 && !strcmp("-classpath", argv[1])) {
- options[0].optionString = strcat(classpath, argv[2]);
- vm_args.nOptions++;
- mainclass_index += 2;
- } else if (env_classpath) {
- options[0].optionString = strcat(classpath, env_classpath);
- vm_args.nOptions++;
- }
- if (vm_args.nOptions > 0) {
- vm_args.options = options;
- }
- if (mainclass_index >= argc) {
- printf("Main class not found, please specify it\n");
- return 0;
- }
- jint res = JNI_CreateJavaVM(&jvm, (void **)&env, &vm_args);
- if (res < 0) {
- printf("Create Java VM error, code = %d\n", res);
- return -1;
- }
- jclass cls = (*env)->FindClass(env, argv[mainclass_index]);
- if (!cls) {
- printf("Class %s not found\n", argv[mainclass_index]);
- return -1;
- }
- jmethodID mid = (*env)->GetStaticMethodID(env, cls, "main", "([Ljava/lang/String;)V");
- if (!mid) {
- printf("Method %s of Class %s not found\n", "main", argv[mainclass_index]);
- return -1;
- }
- applicationArgs = (*env)->NewObjectArray(env, argc - mainclass_index - 1,
- (*env)->FindClass(env, "java/lang/String"),
- NULL);
- int i = 0;
- for (i = mainclass_index + 1; i < argc; i ++) {
- appArg = (*env)->NewStringUTF(env, argv[i]);
- (*env)->SetObjectArrayElement(env, applicationArgs, i - mainclass_index - 1, appArg);
- }
- (*env)->CallStaticVoidMethod(env, cls, mid, applicationArgs);
-
- printf("before destroy\n");
- /*
- * Destroy the JVM.
- * This is necessary, otherwise if the called method exits,
- * this program will return immediately.
- */
- (*jvm)->DestroyJavaVM(jvm);
- printf("after destroy\n");
- return 0;
- }
二、编译,书写makefile文件 ,注意要链接JDK中所自带的jvm.so文件,“-L/usr/lib64/jvm/java-1_6_0-ibm-1.6.0/jre/bin/classic”
- all:CCallJava
- CCallJava:
- gcc -o CCallJava CCallJava.c -I/usr/lib64/jvm/java-1_6_0-ibm-1.6.0/include/ -I/usr/lib64/jvm/java-1_6_0-ibm-1.6.0/include/linux/ -L/usr/lib64/jvm/java-1_6_0-ibm-1.6.0/jre/bin/classic -ljvm -ldl
三、修改.bash_profile文件,设置环境变量,即libjvm.so 所在的路径
export LD_LIBRARY_PATH=/usr/lib64/jvm/java-1_6_0-ibm-1.6.0/jre/bin/classic
四、运行命令./CCallJava -classpath . Test 34 67
结果如下

至此,C语言调用Java程序完成
参考资料:
http://supermmx.org/blog/20060811_calling_java_from_c_cplusplus
本文详细介绍了如何在Linux环境下使用C语言调用Java程序。首先,通过编写C文件模拟JDK的java命令,设置VM参数和类路径。然后,编译C文件并书写makefile,确保链接JDK的jvm.so库。接着,修改.bash_profile文件设置环境变量。最后,运行示例命令完成调用。参考链接提供更多信息。
&spm=1001.2101.3001.5002&articleId=48180831&d=1&t=3&u=699241803a3a46d3a8c46a6beaadbe54)
497

被折叠的 条评论
为什么被折叠?



