Home  >  Article  >  Backend Development  >  How can I call Java methods from C applications?

How can I call Java methods from C applications?

Barbara Streisand
Barbara StreisandOriginal
2024-11-10 09:47:02259browse

How can I call Java methods from C   applications?

Interfacing Java and C : Calling Java Methods from C

The ability to call Java functions from within C applications is indeed possible but requires a somewhat intricate approach. This reflective and non-type-safe mechanism involves creating a Java Virtual Machine (JVM) instance from the C code.

Creating a JVM Instance

The code snippet below demonstrates how to set up a JVM instance:

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);

Interacting with Java Objects

Once the JVM instance is created, you can interact with Java objects. Here's an example of creating a Java String object:

jstring jstr = env->NewStringUTF("Hello World");

Accessing Java Methods

To access a Java method, you need to first get the class that contains the method:

jclass clazz = env->FindClass("java/lang/String");

Then, obtain the method ID:

jmethodID to_lower = env->GetMethodID(clazz, "toLowerCase", "()Ljava/lang/String;");

Calling the Java Method

Finally, call the method on the object:

jobject result = env->CallObjectMethod(jstr, to_lower);

Compilation

On Ubuntu, compile the code using:

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

Conclusion

This approach allows you to access Java methods from C applications, enabling interoperability between the two languages. However, it's crucial to implement proper error handling for robustness.

The above is the detailed content of How can I call Java methods from C applications?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn