Home >Backend Development >C++ >How to Correctly Call a Java Method from Native C in Android?

How to Correctly Call a Java Method from Native C in Android?

DDD
DDDOriginal
2024-11-03 20:33:29380browse

How to Correctly Call a Java Method from Native C   in Android?

Calling a Java Method from C in Android

In Android development, integrating native C functions with Java components is a common requirement. This article will address a specific issue that arises when attempting to call a Java method from C .

Problem:

When trying to invoke a Java method, specifically messageMe, from native code during the execution of the getJniString method, the application encounters a NoSuchMethodError exception.

Java Code:

<code class="java">public class MainActivity extends Activity {
    // ... (Java code to setup and load native library)

    public void messageMe(String text) {
        System.out.println(text);
    }
    // ... (Other Java code)
}</code>

Native C Code (native.cpp):

<code class="c++">// ... (Native C++ code to create a Java String)

// Get the class and method with the incorrect invocation
jclass clazz = env->FindClass("the/package/MainActivity");
jmethodID messageMe = env->GetMethodID(clazz, "messageMe", "(Ljava/lang/String;)V");
jobject result = env->CallObjectMethod(jstr, messageMe); // Incorrect invocation

// Corrected invocation
jobject result = env->CallObjectMethod(obj, messageMe, jstr);</code>

Solution:

The error arises due to an incorrect invocation of the CallObjectMethod function in the native C code. To call an instance method, you need to pass the object to the method as an argument. In this case, the object is obj, which represents the instance of the Java class.

The corrected invocation should be:

<code class="c++">jobject result = env->CallObjectMethod(obj, messageMe, jstr);</code>

The above is the detailed content of How to Correctly Call a Java Method from Native C in Android?. 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