In the realm of cross-platform development, it may arise that a C application requires access to functionalities provided by Java methods. This query explores the feasibility and nuances of achieving this integration.
Feasibility and Mechanism
Yes, it is possible to call Java methods from within C/C code. However, the procedure is somewhat intricate and adheres to a reflective and non-type-safe approach.
The C Application Programming Interface (API) provides a cleaner method for achieving this integration. The approach involves instantiating a Java Virtual Machine (JVM) within the C code. In scenarios where the native code is invoked from Java, constructing a VM instance is unnecessary.
Implementation
The provided code snippet demonstrates how to call Java methods from a C application:
#include <jni.h> #include <stdio.h> int main() { JavaVM *vm; // Pointer to JVM JNIEnv *env; // JNI interface to interact with JVM JavaVMInitArgs vm_args; // JVM initialization arguments // Initialize JVM arguments vm_args.version = JNI_VERSION_1_2; vm_args.nOptions = 0; vm_args.ignoreUnrecognized = 1; // Construct a Java Virtual Machine jint res = JNI_CreateJavaVM(&vm, (void **)&env, &vm_args); // Create a Java string object jstring jstr = env->NewStringUTF("Hello World"); // Get the "java/lang/String" class jclass clazz = env->FindClass("java/lang/String"); // Get the "toLowerCase()" method ID jmethodID to_lower = env->GetMethodID(clazz, "toLowerCase", "()Ljava/lang/String;"); // Invoke the "toLowerCase()" method on the string object jobject result = env->CallObjectMethod(jstr, to_lower); // Convert the Java string to a C-style string const char* str = env->GetStringUTFChars((jstring) result, NULL); // Print the converted string printf("%s\n", str); // Release the C-style string env->ReleaseStringUTFChars(jstr, str); // Destroy the Java Virtual Machine vm->DestroyJavaVM(); return EXIT_SUCCESS; }
Cross-Platform Compilation
For cross-platform compilation on Ubuntu, execute the following command:
g++ -I/usr/lib/jvm/java-6-sun/include \ -I/usr/lib/jvm/java-6-sun/include/linux \ -L/usr/lib/jvm/java-6-sun/jre/lib/i386/server/ -ljvm jnitest.cc
Error Handling
It is crucial to verify the return codes of all methods used for proper error handling. For instance, the following code snippet checks for potential memory allocation issues when retrieving the C-style string:
str = env->GetStringUTFChars(jstr, NULL); if (str == NULL) { return EXIT_FAILURE; /* out of memory */ }
The above is the detailed content of How to Call Java Methods from C Applications?. For more information, please follow other related articles on the PHP Chinese website!