I am not able to consume functions of a "C" lib using Java with JNI. Here are my artifacts and the error generated.
Class CalculadoraJNI
:
public class CalculadoraJNI {
// Declaração do método nativo:
public native int calcula (int num1, int num2);
static {
System.loadLibrary("calcula");
}
File TesteCalculadoraJNI.java
public class TesteCalculadoraJNI {
public static void main (String args[]) {
CalculadoraJNI calc = new CalculadoraJNI();
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
int resultado = calc.calcula(num1, num2);
System.out.println("A soma é: " + resultado);
}
}
After constructing the classes, I executed the following sequence of commands:
javac CalculadoraJNI.java
javac TesteCaculadoraJNI.java
javah CalculadoraJNI
File generated by the javah commander JNI
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class CalculadoraJNI */
#ifndef _Included_CalculadoraJNI
#define _Included_CalculadoraJNI
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: CalculadoraJNI
* Method: calcula
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_CalculadoraJNI_calcula
(JNIEnv *, jobject, jint, jint);
#ifdef __cplusplus
}
#endif
#endif
File calculaJNI.c
:
#include <stdio.h>
#include "CalculadoraJNI.h"
/*
* Método que executa a soma
*/
int calcula (int num1, int num2) {
int resultado = num1 + num2;
return resultado;
}
/*
* Método com a mesma assinatura do calculadoraJNI.h
*/
JNIEXPORT jint JNICALL Java_CalculadoraJNI_calcula
(JNIEnv * env, jobject jobj, jint num1, jint num2)
{
return calcula (num1, num2);
}
Compiling the "C" code:
gcc -o libcalcula.so -shared -I/usr/lib/jvm/java-7-openjdk-amd64/include calculaJNI.c -fPIC
Error generated while trying to run:
Exception in thread "main" java.lang.UnsatisfiedLinkError: no calcula in java.library.path
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1886)
at java.lang.Runtime.loadLibrary0(Runtime.java:849)
at java.lang.System.loadLibrary(System.java:1088)
at CalculadoraJNI.<clinit>(CalculadoraJNI.java:5)
at TesteCalculadoraJNI.main(TesteCalculadoraJNI.java:3)