3
Personal I am not managing to consume functions of a lib in "C" using Java with JNI. Follow 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");
}
Filing cabinet 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 class construction I executed the following sequence of commands:
javac CalculadoraJNI.java
javac TesteCaculadoraJNI.java
javah CalculadoraJNI
File generated by the javah Caculadorajni command
/* 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
Filing cabinet 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);
}
Compilation of code "C":
gcc -o libcalcula.so -shared -I/usr/lib/jvm/java-7-openjdk-amd64/include calculaJNI.c -fPIC
Error generated when 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)
Matheus, thanks for the help, but the solution was to point the environment variable "LD_LIBRARY_PATH" to the directory where the native library was. From what I could notice the method System.loadLibrary() observes this variable to load the code in "C" (native library).
– Canatto Filipe