How to call a Java method from native code
suggest changeThe Java Native Interface (JNI) allows you to call Java functions from native code. Here is a simple example of how to do it:
Java code:
package com.example.jniexample;
public class JNITest {
public static int getAnswer(boolean flag) {
return 42;
}
}
Native code:
int getTheAnswer(JNIEnv *env)
{
// Find the Java class - provide package ('.' replaced with '/') and class name
jclass jniTestClass = env->FindClass("com/example/jniexample/JNITest");
// Parameters go inside (). The return type follows. See the table below.
jmethodID getAnswerMethod = env->GetStaticMethodID(jniTestClass, "getAnswer", "(Z)I");
// CallStaticIntMethod matches the int return. CallStaticObjectMethod is for objects.
return env->CallStaticIntMethod(jniTestClass, getAnswerMethod, (jboolean)JNI_TRUE);
}
JNIEnv* is passed into native methods. JniGetEnv() is not an NDK function.
JNI method signature to Java type:
| JNI signature | Java type |
|---|---|
Z |
boolean |
B |
byte |
C |
char |
S |
short |
I |
int |
J |
long |
F |
float |
D |
double |
Lfully/qualified/Class; |
a class |
[type |
type[] |
(Z)I means the method takes a boolean and returns an int. A semicolon belongs after a class name, not after I.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents