Created
November 9, 2014 05:01
-
-
Save sheimi/593592bc207d1664eb88 to your computer and use it in GitHub Desktop.
code in blog.sheimi.me: hello JNI
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
//Here is HelloJNI.java | |
public class HelloJNI { | |
static { | |
try { | |
Class c = HelloJNI.class; | |
URL location = | |
c.getProtectionDomain().getCodeSource().getLocation(); | |
ZipFile zf = new ZipFile(location.getPath()); | |
// libhellojni.so is put in the lib folder | |
InputStream in = zf.getinputStream(zf.getEntry("lib/libhellojni.so")); | |
File f = File.createTempFile("JNI-", "Temp"); | |
FileOutputStream out = new FileOutputStream(f); | |
byte [] buf = new byte[1024]; | |
int len; | |
while ((len = in.read(buf)) > 0) | |
out.write(buf, 0, len); | |
in.close(); | |
out.close(); | |
System.load(f.getAbsolutePath()); | |
f.delete(); | |
} catch (Exception e) { // I am still lazy ~~~ | |
e.printStackTrace(); | |
} | |
} | |
public static native String showMessage(String msg); | |
public static void main(String [] args) { | |
String msg = HelloJNI.showMessage("Hello JNI"); | |
System.out.println("Here is in Java"); | |
System.out.println(msg); | |
} | |
} |
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
//Here is hellojni.c | |
#include "stdio.h" | |
#include "hellojni.h" | |
JNIEXPORT jstring JNICALL | |
Java_HelloJNI_showMessage(JNIEnv * env, | |
jclass classObject, | |
jstring valueObject) | |
{ | |
fprintf(stdout, "Here is C output\n"); | |
return valueObject; | |
} |
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
//Here is HelloJNI.java | |
public class HelloJNI { | |
static { | |
try { | |
System.loadLibrary("hellojni"); | |
} catch (Exception e) { // I am a little indolent | |
e.printStackTrace(); | |
} | |
} | |
public static native String showMessage(String msg); | |
public static void main(String [] args) { | |
String msg = HelloJNI.showMessage("Hello JNI"); | |
System.out.println("Here is in Java"); | |
System.out.println(msg); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment