Last active
November 13, 2024 20:57
-
-
Save gauravssnl/fe0c217e0ca42bb01b59cc93c417973e to your computer and use it in GitHub Desktop.
JNI example to call java method (example : System.out.println)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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"); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output :
❯ javac Test.java && java -Djava.library.path=. Test
Hello from JNI!
Test OK
Hello String from JNI