Skip to content

Instantly share code, notes, and snippets.

@sheimi
Created November 9, 2014 05:01
Show Gist options
  • Save sheimi/593592bc207d1664eb88 to your computer and use it in GitHub Desktop.
Save sheimi/593592bc207d1664eb88 to your computer and use it in GitHub Desktop.
code in blog.sheimi.me: hello JNI
//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);
}
}
//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;
}
//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