Skip to content

Instantly share code, notes, and snippets.

@gauravssnl
Last active November 13, 2024 20:57
Show Gist options
  • Save gauravssnl/fe0c217e0ca42bb01b59cc93c417973e to your computer and use it in GitHub Desktop.
Save gauravssnl/fe0c217e0ca42bb01b59cc93c417973e to your computer and use it in GitHub Desktop.
JNI example to call java method (example : System.out.println)
#include "jni.h"
void println_java(JNIEnv *env, const char *msg);
extern "C" jint JNI_OnLoad(JavaVM *jvm, void *) {
JNIEnv *env = nullptr;
jvm->GetEnv((void **)&env, JNI_VERSION_1_6);
println_java(env, "Hello from JNI!");
return JNI_VERSION_1_6;
}
void println_java(JNIEnv *env, const char *msg) {
// Get system class
jclass syscls = env->FindClass("java/lang/System");
// Lookup the "out" field
jfieldID fid = env->GetStaticFieldID(syscls, "out", "Ljava/io/PrintStream;");
jobject out = env->GetStaticObjectField(syscls, fid);
// Get PrintStream class
jclass pscls = env->FindClass("java/io/PrintStream");
// Lookup printLn(String)
jmethodID mid = env->GetMethodID(pscls, "println", "(Ljava/lang/String;)V");
// Invoke the method
jstring str = env->NewStringUTF(msg);
env->CallVoidMethod(out, mid, str);
}
extern "C" JNIEXPORT jstring JNICALL Java_Test_stringFromJNI(JNIEnv *env,
jobject thiz) {
return env->NewStringUTF("Hello String from JNI");
}
export CPLUS_INCLUDE_PATH="$JAVA_HOME/include:$JAVA_HOME/include/linux"
clang hello.cpp -shared -o libhello.so
javac Test.java && java -Djava.library.path=. Test
class Test {
static {
System.loadLibrary("hello");
}
public static void main(String[] args) {
System.out.println("Test OK");
System.out.println(stringFromJNI());
}
public static String message() {
return "Hello from Java";
}
public native static String stringFromJNI();
}
@gauravssnl
Copy link
Author

Output :
❯ javac Test.java && java -Djava.library.path=. Test
Hello from JNI!
Test OK
Hello String from JNI

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment