Created
October 7, 2016 21:33
-
-
Save dhilst/3772bbad1bd86f1480d180c78947c173 to your computer and use it in GitHub Desktop.
RegisterNatives JNI example
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 <jni.h> | |
| #include <iostream> | |
| #include <string> | |
| using namespace std; | |
| extern "C" | |
| JNIEXPORT void JNICALL sayHello(JNIEnv *env, jclass cls, jstring arg) | |
| { | |
| const char *raw = env->GetStringUTFChars(arg, NULL); | |
| string s(raw); | |
| env->ReleaseStringUTFChars(arg, raw); | |
| cout << "Hello, " << s << endl; | |
| } | |
| static JNINativeMethod methods[] = { | |
| { const_cast<char *>("sayHello"), const_cast<char *>("(Ljava/lang/String;)V"), reinterpret_cast<void *>(&sayHello) }, | |
| }; | |
| extern "C" | |
| JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *pvt) | |
| { | |
| JNIEnv *env = NULL; | |
| if (vm->GetEnv((void **)&env, JNI_VERSION_1_2) != JNI_OK) { | |
| throw "Cannot get Java env"; | |
| } | |
| jclass cls = env->FindClass("RegisterNativesExample"); | |
| if (!cls) | |
| env->FatalError("Cannot file RegisterNativesExample class"); | |
| env->RegisterNatives(cls, methods, 1); | |
| return JNI_VERSION_1_2; | |
| } |
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-7-openjdk | |
| CXXFLAGS += -Wall | |
| CXXFLAGS += -I. -I$(JAVA_HOME)/include -I$(JAVA_HOME)/include/linux | |
| all: libregisternatives.so RegisterNativesExample.class | |
| clean: | |
| rm RegisterNativesExample.class libregisternatives.so | |
| libregisternatives.o: libregisternatives.cpp | |
| libregisternatives.so: libregisternatives.o | |
| RegisterNativesExample.class: RegisterNativesExample.java | |
| %.o: %.cpp | |
| $(CXX) $(CXXFLAGS) $(LDFLAGS) -fPIC -c $< | |
| %.so: %.o | |
| $(CXX) $(CXXFLAGS) $(LDFLAGS) -shared -o $@ $< | |
| %.class: %.java | |
| javac $< | |
| %.h: %.class | |
| javah -cp . $(<:.class=) |
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
| public class RegisterNativesExample { | |
| static { | |
| System.loadLibrary("registernatives"); | |
| } | |
| static native void sayHello(String args); | |
| static public void main(String[] args) { | |
| sayHello("World"); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment