C語言呼叫 Java(Linux)
阿新 • • 發佈:2019-02-03
一、書寫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
- if (argc >= 3 && !strcmp("-classpath", argv[1])) {
- options[0].optionString = strcat(classpath, argv[2]);
- vm_args.nOptions++;
- mainclass_index += 2;
- } elseif (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