Skip to content

Instantly share code, notes, and snippets.

@dhilst
Created October 3, 2016 01:45
Show Gist options
  • Select an option

  • Save dhilst/b29d6703d8bbc0e5b626ba56e23a0838 to your computer and use it in GitHub Desktop.

Select an option

Save dhilst/b29d6703d8bbc0e5b626ba56e23a0838 to your computer and use it in GitHub Desktop.
JNI Callback
interface CallbackInterface {
public void callback();
}
public class Callback {
static native void nativeCallJavaMethod(CallbackInterface cb);
public static void main(String []args) {
System.loadLibrary("callback");
/* Passing code as argument */
nativeCallJavaMethod(new CallbackInterface() {
public void callback() {
System.out.println("Hello from CallbackInterface");
}
});
}
}
#include "Callback.h"
JNIEXPORT void JNICALL Java_Callback_nativeCallJavaMethod
(JNIEnv *env, jclass cls, jobject impl_obj)
{
jclass impl_cls;
jmethodID impl_cb_mid;
impl_cls = (*env)->GetObjectClass(env, impl_obj);
if (!impl_cls)
return;
impl_cb_mid = (*env)->GetMethodID(env, impl_cls, "callback", "()V");
if (!impl_cb_mid)
return;
(*env)->CallVoidMethod(env, impl_obj, impl_cb_mid);
}
JAVA_HOME := /usr/lib/jvm/java-8-openjdk-amd64
CFLAGS += -I$(JAVA_HOME)/include -I$(JAVA_HOME)/include/linux
all: libcallback.so
libcallback.so: libcallback.c Callback.h
Callback.h: Callback.class
Callback.class: Callback.java
%.class: %.java
javac $<
%.h: %.class
javah $(<:.class=)
%.so: %.c
$(CC) $(CFLAGS) $(LDFLAGS) -fPIC -shared -o $@ $^
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment