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
Release: 2024-11-03 20:33:29
Original
384 people have browsed it

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

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template