Skip to content

Instantly share code, notes, and snippets.

@LongClipeus
Last active June 22, 2024 02:13
Show Gist options
  • Save LongClipeus/43c98b18f9814381825b1a225ab5e49e to your computer and use it in GitHub Desktop.
Save LongClipeus/43c98b18f9814381825b1a225ab5e49e to your computer and use it in GitHub Desktop.
Example JNI/C++ Hello World in Ubuntu
public class HelloJNI {
static {
System.loadLibrary("hello"); // load libhello.so
}
private native void sayHello();
public static void main(String[] args) {
new HelloJNI().sayHello();
}
}
#include <iostream>
#include <jni.h>
#include "HelloJNI.h" // auto-generated by `javah HelloJNI`
using namespace std;
JNIEXPORT void JNICALL Java_HelloJNI_sayHello (JNIEnv *, jobject) {
cout << "Hello world. My name is Roboss" << endl;
return;
}

export JAVA_INC=/usr/lib/jvm/java-8-oracle/include

Step 1: compile the .class file and auto-generate a .h header file

javac -h . HelloJNI.java

Step 2: make the shared library with the name linked in said Java source, and implementing said native method

g++ -std=c++11 -shared -fPIC -I$JAVA_INC -I$JAVA_INC/linux HelloJNIImpl.cpp -o libhello.so

Step 3: run JVM with java.library.path set to include said shared library

java -Djava.library.path=. HelloJNI

Learn more

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