使用jna

时间:2018-05-15 15:09:54

标签: java c++ global-variables jna .so

我实际上是在尝试打开一个库。所以(我用c ++做过)用JNA 我的问题是,当有静态变量时我无法打开库。但是我必须在我的库中使用un singleton所以我正在寻找为什么静态变量不能与JNA一起使用以证明它是一个小型库

有.h文件:

#ifndef UNTITLED1_LIBRARY_H
#define UNTITLED1_LIBRARY_H
#include <iostream>
class library {
 private:
  static char* h;
 public:
  int hello();
};

extern "C" int hello(){
 library lib;
 return lib.hello();
}

#endif

然后我的.cpp文件:

#include "library.h"
#include "ecrire.h"

#include <iostream>

int library::hello() {
 h = (char*)"hello world";
 std::cout<<h<<std::endl;
 return 45;
}

然后是我的java类和接口

public class Westgard {
static {       
    System.setProperty("jna.library.path","../logic/resources/calculator"); 
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int maj = InterfaceLibWestgard.INSTANCE.hello();
    System.out.println(maj);
}

}


import com.sun.jna.Library;
import com.sun.jna.Native;

public interface InterfaceLibWestgard extends Library {
  int hello();
  static InterfaceLibWestgard INSTANCE = (InterfaceLibWestgard) 
  Native.loadLibrary("../logic/resources/calculator/libuntitled1.so", 
  InterfaceLibWestgard.class);
}

因此,如果我尝试这样做它不会工作但是当从.h中移除静电时,它的工作原理并不知道为什么我一直在寻找,因为4-5小时仍然不知道为什么......

这是我的问题日志:

Exception in thread "main" java.lang.UnsatisfiedLinkError: Unable to load 
 library '../logic/resources/calculator/libuntitled1.so': Native library 
(linux-x86-64/../logic/resources/calculator/libuntitled1.so) not found in 
resource path ([file:/opt/java/jdk1.8.0_151/jre/lib/resources.jar, 

2 个答案:

答案 0 :(得分:1)

您已声明library::h但未对其进行定义。你需要添加

char* library::h = 0;

在您的cpp文件中。

据推测,该库要么无法编译,要么正在编译,但期望在另一个库中定义此缺失符号。

答案 1 :(得分:0)

您可以使用 Native.load() 代替 Native.loadLibrary()

检查下面的代码,

    public interface MyLibrary extends Library {
        int myMethod();
    }

    static {
        MyLibrary lib = (MyLibrary)Native.load("untitled1" , MyLibrary.class);
    }

您可以将文件添加到资源位置并通过上述方式轻松加载。您应该排除“lib”前缀和“.so”文件类型。就你而言,

filename = "untitled1"

Using JNA to Access Native Dynamic Libraries