为什么它甚至可以编译? - 使用 swig 生成的 类 从 java 编译和 运行 本机方法

Why does it even compile? - Compile and run native method from java using swig generated classes

所以我已经按照 this Swig 教程生成 JNI 代理 class 和共享库。结果我得到了 libexmple.so 文件。

Building a Java module教程部分你可以看到。

 $ swig -java example.i
 $ gcc -c example.c example_wrap.c -I/c/jdk1.3.1/include -I/c/jdk1.3.1/include/win32
 $ gcc -shared example.o  example_wrap.o -mno-cygwin -Wl,--add-stdcall-alias  -o example.dll
 $ cat main.java

 public class main {
       public static void main(String argv[]) {
         System.loadLibrary("example");
         System.out.println(example.getMy_variable());
         System.out.println(example.fact(5));
         System.out.println(example.get_time());
       }
 }

 $ javac main.java
 $ java main
 3.0
 120
 Mon Mar  4 18:20:31  2002

3.0、120 和 Mon Mar 4 18:20:31 2002 是函数结果。

老实说,我什至没想到它会编译,但它确实编译了,而且 当我执行 java main 时,它运行没有问题所以我的第一个问题是? java如何知道println方法调用

中的"example"是什么
System.out.println(example.getMy_variable());

当我尝试通过 Intellij IDE 编译它时,自然会抛出一个错误 "could not find symbol example"我应该扔。

第二次尝试以这种方式使用这个库时

public class Main {

static {
    try {
        System.loadLibrary("example");
        System.out.println("lib initialized");
    } catch (Exception e) {
        System.out.println(e.toString());
    }

}

public static native void My_variable_set(double jarg1);

public static native double My_variable_get();

public static native int fact(int jarg1);

public static native int my_mod(int jarg1, int jarg2);

public static native String get_time();

public static void main(String args[]) {
    try {
        Main.fact(3);
        System.out.println("method called successfully");
    } catch (Exception e) {
        System.out.println(e.toString());
    }

}

我得到

Exception in thread "main" java.lang.UnsatisfiedLinkError: test.Main.fact(I)I

尝试调用本机方法时。

我确信 lib 已正确加载(获取 lib 初始化日志)。当我尝试加载不存在时出现不同的错误(class 加载异常)

java.lang.UnsatisfiedLinkError: no exampleld in java.library.path

为什么它甚至可以编译?

因为javac可以看出main使用classexample 来自同一个 并编译它。实际上,它还找到 class exampleJNI,它也是由 swig 自动生成的,并在 中使用]example.java.

java如何知道println方法调用中的"example"是什么?

在Java中,你不需要import对于class在同一个包中的,这就是java 知道调用 example.getMy_variable().

当我尝试使用这个库时,出现异常

您尝试将本机方法从 exampleJNI.java 移动到 main.java 失败,因为对于 JNI, class 的名称用于确定本机函数的名称。如果查看 example.dll.

的导出函数列表,您可以看到它

如果您想使用 swig,只需使用它生成的文件即可。如果您想更好地了解 JNI 的工作原理,请阅读书籍或在线文档,遵循教程等。不要尝试使用 swig 不是什么:JNI 编程简介.