【问题标题】:load lib .so with jna用 jna 加载 lib .so
【发布时间】:2018-05-15 15:09:53
【问题描述】:

我实际上是在尝试打开一个库。所以(我用 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, 

【问题讨论】:

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


    【解决方案1】:

    您已声明 library::h 但未定义它。你需要添加

    char* library::h = 0;
    

    在您的 cpp 文件中。

    推测该库要么编译失败,要么正在编译,但希望在另一个库中定义这个丢失的符号。

    【讨论】:

    【解决方案2】:

    您可以使用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

    【讨论】:

      猜你喜欢
      • 2016-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多