JNI + MAC OS X: Simple sample

Couple things to be aware of:

#1. for MAC OS X, the binaries end with .dylib or .jnilib (not .so, .dll)
#2. when compiling the shared lib, you should split up the compilation from the linking
#3. when compiling the shared lib in MAC OS X, be sure to specify the JavaVM framework

The code is like every other JNI example, so I wont post it here. The actual problem was in the command-prompt commands... which should go something like this:

javac HelloWorld.java
javah -jni HelloWorld
cc -c -I/Library/Java/Home/include helloworld.c
cc -dynamiclib -o libhelloworld.jnilib helloworld.o -framework JavaVM
java HelloWorld

5 simple lines...

Do not use the following line to compile for MAC OS X, it will give you all sorts of complaints:
[g]cc -dynamiclib [-G] [-m32] -o helloworld.dylib -I/Library/Java/Home/include [-arch i386] helloworld.c

Again.. DO SEPARATE the COMPILATION and the LINKING steps!!!

These are common error messages that spawn from the above command...

Exception in thread "main" java.lang.UnsatisfiedLinkError: no helloworld in java.library.path (missing javavm definition)

Exception in thread "main" java.lang.UnsatisfiedLinkError: no suitable image found. Did find: ... mach-o, but wrong architecture (ironically, not really caused by wrong architecture)

Exception in thread "main" java.lang.UnsatisfiedLinkError: no suitable image found. Did find: ... can't map (happens when you use wrong architecture)

ld: library not found for -l..., collect2: ld returned 1 exit status

Undefined symbols: "_main", referenced from: start in crt1.10.6.o, ld: symbol(s) not found, collect2: ld returned 1 exit status



5 comments:

Paul said...
This comment has been removed by the author.
Paul said...

Great example. Using Lion, I used this include path:

cc -c -I/System/Library/Frameworks/JavaVM.framework/Headers/ HelloWorld.c

Unknown said...

sorry i tried u r appraoch but still but i am getting


Exception in thread "main" java.lang.UnsatisfiedLinkError: no libMYJNIImpl.jnilib in java.library.path

rair said...

Paul, I could kiss your feet. I've spent days trying to get this to work, and then suddenly my eyes alighted upon your comment... I still have no idea what was wrong with my path/command, but yours worked on Snow Leopard, too. The rest of the OP's instructions worked.

Aditya Singh said...

Woah man. U rock. :-D