Invoking Java Methods from C Applications
In the realm of cross-platform integration, the ability to seamlessly interact between different programming languages becomes paramount. One such scenario involves calling Java functions from within C applications.
While not straightforward, this feat is indeed achievable through a reflective approach. By leveraging Java's Native Interface (JNI), C can interact with the Java Virtual Machine (JVM). Here's a detailed explanation of the process:
Create a Java Virtual Machine (JVM):
Obtain the Java Object:
Locate the Java Method:
Call the Java Method:
Extract the Result:
Clean Up:
Example Code:
#include <jni.h> #include <stdio.h> int main() { JavaVM *vm; JNIEnv *env; JavaVMInitArgs vm_args; vm_args.version = JNI_VERSION_1_2; vm_args.nOptions = 0; vm_args.ignoreUnrecognized = 1; // Construct a VM jint res = JNI_CreateJavaVM(&vm, (void **)&env, &vm_args); // Construct a String jstring jstr = env->NewStringUTF("Hello World"); // Find the class and method jclass clazz = env->FindClass("java/lang/String"); jmethodID to_lower = env->GetMethodID(clazz, "toLowerCase", "()Ljava/lang/String;"); // Call the method jobject result = env->CallObjectMethod(jstr, to_lower); // Get the C-style string const char *str = env->GetStringUTFChars((jstring)result, NULL); printf("%s\n", str); // Clean up env->ReleaseStringUTFChars(jstr, str); vm->DestroyJavaVM(); return 0; }
To compile the code on Linux, run:
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
Note: Implement proper error handling by checking the return codes of JNI methods.
The above is the detailed content of How can Java methods be invoked from C applications?. For more information, please follow other related articles on the PHP Chinese website!