Search code examples
javac++makefilejava-native-interface

Add lib to makefile for jni app


I don't understand how to run c++ code in java using JNI. I think there's some error in the makefile, I think some lib are missing.

I have this code in java class:

private native void getCanny(long mat);
getCanny(mat.getNativeObjAddr());

and the Mat2Image.h generated:

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

#ifndef _Included_Mat2Image
#define _Included_Mat2Image
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     Mat2Image
 * Method:    getCanny
 * Signature: (J)V
 */
JNIEXPORT void JNICALL Java_Mat2Image_getCanny
  (JNIEnv *, jobject, jlong);

#ifdef __cplusplus
}
#endif
#endif

and this is the .cpp I've made:

#include "Mat2Image.h"
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc.hpp>


JNIEXPORT void JNICALL Java_Mat2Image_getCanny
   (JNIEnv * env, jobject obj, jlong matr){


       cv::Mat* frame=(cv::Mat*)matr;
            cv::cvtColor(*frame, *frame, CV_BGR2GRAY);
            cv::GaussianBlur(*frame, *frame, cv::Size(7,7), 1.5, 1.5);
            cv::Canny(*frame, *frame, 0, 30, 3);


}

and this is my makefile:

# Define a variable for classpath
CLASS_PATH = ../bin

# Debug: -g3=compile with extra debugg infos. -ggdbg3=include things like macro defenitions. -O0=turn off optimizations.
DEBUGFLAGS = -g3 -ggdb3 -O0
CFLAGS = $(DEBUGFLAGS)

# Define a virtual path for .class in the bin directory
vpath %.class $(CLASS_PATH)

all : libMat.so

# $@ matches the target, $< matches the first dependancy
libMat.so : libMat.o
    g++ $(CFLAGS) -W -shared -o $@ $<

# $@ matches the target, $< matches the first dependancy
libMat.o : Mat2Image.cpp Mat2Image.h
    g++ $(CFLAGS) -fPIC -I/usr/lib/jvm/jdk1.8.0_111/include -I/usr/lib/jvm/jdk1.8.0_111/include/linux -c $< -o $@

# $* matches the target filename without the extension
# manually this would be: javah -classpath ../bin HelloJNI
HelloJNI.h : Mat2Image.class
    javah -classpath $(CLASS_PATH) $*

clean :
    rm -f Mat2Image.h libMat.o libMat.so

but when I try to run the method I have this error:

/usr/lib/jvm/jdk1.8.0_111/bin/java: symbol lookup error: /home/buzzo/Downloads/helloJni-master/jni/libMat.so: undefined symbol: _ZN2cv8cvtColorERKNS_11_InputArrayERKNS_12_OutputArrayEii

I think the problem is the makefile, how can I edit it?


Solution

  • It looks like your code is using symbols that are not linked.

    I suggest to link your shared lib with opencv ?

    If you want to look at sample code where shared library is used from JNI, take a look here:

    https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo023

    In your case, it looks like opencv library is not on LD_LIBRARY_PATH.