Created
October 3, 2016 01:45
-
-
Save dhilst/b29d6703d8bbc0e5b626ba56e23a0838 to your computer and use it in GitHub Desktop.
JNI Callback
This file contains hidden or 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
| 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"); | |
| } | |
| }); | |
| } | |
| } |
This file contains hidden or 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 "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); | |
| } |
This file contains hidden or 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
| 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