Blog Archive

Thursday, December 21, 2017

Java Native Interface (JNI) for calling C-libraries

Reference:

https://youtu.be/4B-cNXYNRDo





Step 1: prepare files (printmsg.c & main.java)



cat printmsg.c

#include<stdio.h>



void printmsg()

{

printf("hello there world from Gang\n");

}





cat main.java

class MyMain{

public native void printmsg();

static

{

System.loadLibrary("prtmsg");

}

public static void main(String[] args){

MyMain hello = new MyMain();

hello.printmsg();



}





}





Step 2: compileing caller (JAVA)

javac main.java # output MyMain.class

javah MyMain #output MyMain.h





cat MyMain.h

/* DO NOT EDIT THIS FILE - it is machine generated */

#include <jni.h>

/* Header for class MyMain */



#ifndef _Included_MyMain

#define _Included_MyMain

#ifdef __cplusplus

extern "C" {

#endif

/*

 * Class:     MyMain

 * Method:    printmsg

 * Signature: ()V

 */

JNIEXPORT void JNICALL Java_MyMain_printmsg

  (JNIEnv *, jobject);



#ifdef __cplusplus

}

#endif

#endif





Step 3: re-editing callee (C)

#edit printmsg.c to include "MyMain.h" & modify function signature



#include<stdio.h>

#include "MyMain.h"



//void printmsg(){

JNIEXPORT void JNICALL Java_MyMain_printmsg

  (JNIEnv *env, jobject obj)

{

printf("hello there world from Gang\n");

}





Step 4: compiling callee (C)

gcc -shared -o libprtmsg.so printmessage.c -fPIC -I/usr/lib/jvm/java-1.8.0-openjdk-amd64/include -I/usr/lib/jvm/java-1.8.0-openjdk-amd64/include/linux



Step 5: preparing environment & testing:

cat build.sh

export LD_LIBRARY_PATH=`pwd`

echo $LD_LIBRARY_PATH

unset LD_LIBRARY_PATH

java MyMain





'via Blog this'

No comments:

Post a Comment