use c++ Dll in java program

2019-09-13 10:57发布

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>

标签: java c++ dll
1条回答
Viruses.
2楼-- · 2019-09-13 11:23

Check this thread How to fix an UnsatisfiedLinkError (Can't find dependent libraries) in a JNI project they are also discussing java.lang.UnsatisfiedLinkError

查看更多
登录 后发表回答