Java Native Interface - Examples - HelloWorld

HelloWorld

make.sh

#!/bin/sh # openbsd 4.9 # gcc 4.2.1 # openjdk 1.7.0 JAVA_HOME=$(readlink -f /usr/bin/javac | sed "s:bin/javac::") export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:. javac HelloWorld.java javah HelloWorld gcc -I${JAVA_HOME}/include -shared libHelloWorld.c -o libHelloWorld.so java HelloWorld

HelloWorld.java

class HelloWorld { private native void print; public static void main(String args) { new HelloWorld.print; } static{ System.loadLibrary("HelloWorld"); } }

HelloWorld.h

/* DO NOT EDIT THIS FILE - it is machine generated */ #include /* Header for class HelloWorld */ #ifndef _Included_HelloWorld #define _Included_HelloWorld #ifdef __cplusplus extern "C" { #endif /* * Class: HelloWorld * Method: print * Signature: V */ JNIEXPORT void JNICALL Java_HelloWorld_print (JNIEnv *, jobject); #ifdef __cplusplus } #endif #endif

libHelloWorld.c

#include #include "HelloWorld.h" JNIEXPORT void JNICALL Java_HelloWorld_print(JNIEnv *env, jobject obj) { printf("Hello World!\n"); return; }

chmod +x make.sh
./make.sh

Read more about this topic:  Java Native Interface, Examples