Skip to content

viccomx/jni

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

This is a basic example for using JNI. the project calls four functions written in C from a java class.

Instructions

Compile java classes.

javac JavaCWrapper.java
javac Main.java

Creating C header for calling C methods

javah -jni command is included in jdk. And will create automatically a C header to import and start writing what we need in C code.

javah -jni JavaCWrapper

Output

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class JavaCWrapper */

#ifndef _Included_JavaCWrapper
#define _Included_JavaCWrapper
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     JavaCWrapper
 * Method:    additionFromC
 * Signature: (DD)D
 */
JNIEXPORT jdouble JNICALL Java_JavaCWrapper_additionFromC
  (JNIEnv *, jobject, jdouble, jdouble);
...
...
...

Implement needed C code

#include <jni.h>
#include <stdio.h>

#include "JavaCWrapper.h"

/*
 * Class:     JavaCWrapper
 * Method:    additionFromC
 * Signature: (II)D
 */
JNIEXPORT jdouble JNICALL Java_JavaCWrapper_additionFromC
  (JNIEnv *env, jobject o, jdouble a, jdouble b){
  	return a + b;
}
...
...
...

Compile C code

There are different variants form compiling, as JNI libraries are allocated differently depending on the used OS

MAC OS

The dynamic libraries have .dylib so be sure to use this extension. It can be seen that in JavaCWrapper the imported library is just nvch please avoid problems and call the library as follows: **lib.dylib

gcc -I/System/Library/Frameworks/JavaVM.framework/Versions/Current/Headers -o libnvch.dylib -shared JavaCWrapper.c

The part after -I could change as it only points where jni.h is allocated.

WINDOWS

For windows extension are .dll also don't forget to remove the lib part from the file name.

Linux

Same as in MAC.

Once you successfully run the above command, you will see a libctest.so file in the current directory (or libctest.dylib or libctest.dll).

Run java program

java Main

Missing libraries, are linked dynamically.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • C 58.7%
  • Java 41.3%