Home > Backend Development > C++ > body text

Can I call Java methods from a C application?

Mary-Kate Olsen
Release: 2024-11-13 00:15:02
Original
876 people have browsed it

Can I call Java methods from a C   application?

How to Call Java Methods from C Applications

Problem:

It is possible to invoke functions defined in Java code from a C application?

Answer:

Yes, it is possible to call Java methods from C code, but the process is somewhat complex. This approach utilizes reflection and operates in a non-type-safe manner.

Implementation:

The C code creates an instance of the Java Virtual Machine (JVM) from within the C code. If the native code is invoked from Java, creating a VM instance is unnecessary.

Here is an example of how to access a Java method from C :

#include<jni.h>
#include<stdio.h>

int main(int argc, char** argv) {
    JavaVM *vm;
    JNIEnv *env;
    JavaVMInitArgs vm_args;
    vm_args.version = JNI_VERSION_1_2;
    vm_args.nOptions = 0;
    vm_args.ignoreUnrecognized = 1;

    // Create a JVM
    jint res = JNI_CreateJavaVM(&vm, (void **)&env, &vm_args);

    // Create a Java String object
    jstring jstr = env->NewStringUTF("Hello World");

    // Get the class containing the method to be invoked
    jclass clazz = env->FindClass("java/lang/String");

    // Get the method to be called
    jmethodID to_lower = env->GetMethodID(clazz, "toLowerCase", "()Ljava/lang/String;");

    // Invoke the method on the object
    jobject result = env->CallObjectMethod(jstr, to_lower);

    // Convert the result to a C-style string
    const char* str = env->GetStringUTFChars((jstring) result, NULL);

    printf("%s\n", str);

    // Clean up
    env->ReleaseStringUTFChars(jstr, str);

    // Destroy the JVM
    vm->DestroyJavaVM();

    return 0;
}
Copy after login

Compilation:

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
Copy after login

Note: It is crucial to handle error codes from the JNI methods to implement proper error management.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template