3

I'm trying to use the System.LoadLibrary() to use a simple dll i wrote in c++.

UseDllInJava.java:

import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.NativeLong;
import com.sun.jna.Platform;
import com.sun.jna.*;

/**
 * Created by Amit Baz on 06/06/2016.
 */
public class UseDllInJava {


    static{
        System.loadLibrary("SimpleDll");
    }
    public native static void  HelloFromCPP();

    public static void main(String[] args){


        HelloFromCPP();
    }

}

This is the dll:

SimpleDll.h

#pragma once

namespace SimpleDll
{
    class MyFunctions
    {
    public:
        static __declspec(dllexport) void HelloFromCPP();

    };
}

SimpleDll.cpp:

#include "SimpleDll.h"
#include <stdio.h>
#include <iostream>

using namespace std;

namespace SimpleDll {
    extern "C" {
        void MyFunctions::HelloFromCPP() {
            cout << "Hello from cpp" << endl;
        }
    }
}

I also added the variable

-Djava.library.path="Path\To\SimpleDll" to the VM options in the Intellij run configurations.

But when I run the program it returns the error:

Exception in thread "main" java.lang.UnsatisfiedLinkError: UseDllInJava.HelloFromCPP()V

EDIT

Now it works!

I got help from this tutorial: https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html

Also I didn't know that the JNI naming convention is Java_<Package_name>_<Class_name>_<Function_name>

kitsuneFox
  • 1,243
  • 3
  • 18
  • 31
  • Java can not import c++ function withfor standard api. You can write java plugin using Java DDK (JDK). JDK have many examples. -D option show that your *dll* is *java plugin*, but it's not true. – nick_n_a Jun 06 '16 at 08:48
  • One of JNI examples: http://stackoverflow.com/questions/20328012/c-plugin-jni-java-classpath – nick_n_a Jun 06 '16 at 09:07
  • Try type System.loadLibrary("SimpleDll.dll"), may be work. Runtime.getRuntime().loadLibrary("C:/Windows/System32/crypt32.dll") (http://www.tutorialspoint.com/java/lang/runtime_loadlibrary.htm) – nick_n_a Jun 06 '16 at 09:27
  • @nick_n_a adding ".dll" didn't work. i get "Exception in thread "main" java.lang.UnsatisfiedLinkError: no SimpleDll.dll in java.library.path" error – kitsuneFox Jun 06 '16 at 10:22
  • Then, may I learn what did you exactly do to make it run? I mean what changes did you apply to the code above? – Sarp Engin Daltaban Oct 13 '21 at 08:54

0 Answers0