Search code examples
javac++java-native-interfacecygwin

JNI use .hpp library inside C++


I am trying to use JNI with C++. I'm able to create a Hello-World JNI project following this tutorial.

But, I want to use JSON for modern C++ inside my C++ function. This library contains only a json.hpp file that I include inside my project. Everything compile well, I got my hello.dll file but when I run my Java application, I got this error :

$ java HelloJNI java.lang.UnsatisfiedLinkError: C:\Users\Levio-CIL\Desktop\TEST\hello.dll: Can't find dependent libraries
        at java.lang.ClassLoader$NativeLibrary.load(Native Method)
        at java.lang.ClassLoader.loadLibrary0(Unknown Source)
        at java.lang.ClassLoader.loadLibrary(Unknown Source)
        at java.lang.Runtime.loadLibrary0(Unknown Source)
        at java.lang.System.loadLibrary(Unknown Source)
        at HelloJNI.<clinit>(HelloJNI.java:3) Exception in thread "main"

I did some tests, and it seems that the .dll can't find the function inside json.hpp. When I remove this function, everything works well. The C++ program can also run successfully as a standalone.

HelloJNI.java:

public class HelloJNI {
   static {
      System.loadLibrary("hello"); 
   }

   private native void sayHello();

   public static void main(String[] args) {
      new HelloJNI().sayHello();  // invoke the native method
   }
}

HelloJNI.cpp:

#include <jni.h>
#include "HelloJNI.h"
#include "json.hpp"

using json = nlohmann::json;

// Implementation of native method sayHello() of HelloJNI class
JNIEXPORT void JNICALL Java_HelloJNI_sayHello(JNIEnv *env, jobject thisObj) {

    json specific_data = json::parse("{\"id\": \"aa\",\"value\": 1,\"type\": \"water\"}"); //THE PROBLEMATIC LINE
    printf("Hello world");
    return;
}

Additional Information :

I'm Using Windows 10 with cygwin64.

I compile my c++ file with this command :

x86_64-w64-mingw32-g++ -I"%JAVA_HOME%\include" -I"%JAVA_HOME%\include\win32" -shared -o hello.dll HelloJNI.cpp json.hpp

Every file is inside the same directory.

EDIT : I included missing library provided by Dependency Walker but still got the same error. (And Yes, I run with the .dll inside my workdir)


Solution

  • Try to remove hpp from your command,

    x86_64-w64-mingw32-g++ -I"%JAVA_HOME%\include" -I"%JAVA_HOME%\include\win32" -shared -o hello.dll HelloJNI.cpp
    

    If the error persists, check the DLL dependencies using the Dependency Walker.