Friday, August 10, 2012

JNI : Step-by-step tutorial on OS X with GCC

Here is a simple step-by-step tutorial to write a sample JNI application on Mac OS X using gcc compiler.
Stand alone GCC  (i.e, without Xcode) can be installed from here.

Step 1: Write the java code

public class JniSample {

   public native int sayHello();

   public static void main(String[] args) {

       System.loadLibrary("JniSample");
       System.out.println("In java main");

       JniSample s = new JniSample();
       s.sayHello();
   }
}

Step 2: Compile the java code

$ javac JniSample.java

Step 3: Create the header file

$ jahah JniSample

It looks like:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class JniSample */

#ifndef _Included_JniSample
#define _Included_JniSample
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class:     JniSample
* Method:    sayHello
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_JniSample_sayHello
 (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

Step 4: Write C code

#include <stdio.h>
#include "JniSample.h"

JNIEXPORT jint JNICALL Java_JniSample_sayHello (JNIEnv *env, jobject obj) {
 printf("Hello World\n");
 return 0;
}

Step 5: Compile C code and create native library

$ cc -v -c -fPIC -I/System/Library/Frameworks/JavaVM.framework/Versions/A/Headers/ JniSample.c -o libJniSample.o
$ libtool -dynamic -lSystem libJniSample.o -o libJniSample.dylib

Step 6: Set LD_LIBRARY_PATH env variable:

$ LD_LIBRARY_PATH=.
$ export $LD_LIBRARY_PATH

Step 7: Run

$ java JniSample
In java main
Hello World

Thursday, July 5, 2012

Dired on steroids - Sunrise command mode

Found a nice extension to emacs dired: Sunrise.

If you want to open files in external apps from Sunrise mode add the lines below in your ".emacs"

(defun lx-sunrise-display-external ()
      "Open file at point in an external application."
      (interactive)
      (let ((file (dired-get-filename)))
        (call-process shell-file-name nil nil nil shell-command-switch
                  (format "%s \"%s\"" lx-sunrise-external-viewer file))))
    (setq lx-sunrise-external-viewer "open")
    (define-key sr-mode-map '[\C-return] 'lx-sunrise-display-external)
Now you should be able to open files with external apps with C-return. I have only tried this with OS X Emacs 24.