【问题标题】:java.lang.UnsatisfiedLinkError even though libraries and classes have methodjava.lang.UnsatisfiedLinkError 即使库和类有方法
【发布时间】:2019-06-08 15:59:35
【问题描述】:

我正在使用 Python 和 Py4J 来测试 JNI 代码。但是当我调用 JNI 代码时,出现以下错误:

py4j.protocol.Py4JJavaError: An error occurred while calling o37.createInstance.
: java.lang.UnsatisfiedLinkError: com.mgr_api_JNI.createInstance(Lcom/mgr_api_types$EDisplayType;Ljava/lang/String;Lcom/mgr_api_types$ECommType;Ljava/lang/String;)V
    at com.mgr_api_JNI.createInstance(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:238)
    at java.base/java.lang.Thread.run(Thread.java:834)

我查看了这些链接 link 1link 2link 3link 4link 5link 6 以及其他链接,但没有一个能解决我的问题。

代码

mgr_api_JNI.java:

package com;
import com.mgr_api_types.*;

public class mgr_api_JNI
{
    static
    {
        try
        {
            System.loadLibrary("Mngr"); // Use "-Djava.library.path=[path to library]" option to load this library
        }
        catch (UnsatisfiedLinkError e)
        {
            System.err.println("Native code library 'Mngr' failed to load.\n" + e);
        }
    }

    public native void createInstance(com.mgr_api_types.EDisplayType displayType,
                                      String displaySerialNumber,
                                      com.mgr_api_types.ECommType commType,
                                      String portName);
}

testsJNI.java:

import com.*;
import py4j.GatewayServer;

public class testsJNI
{
    public static void main(String args[])
    {
        testsJNI testApp = new testsJNI();

        // Py4J server
        GatewayServer server = new GatewayServer(testApp);
        server.turnLoggingOff();
        server.start();
    }
}

com_mgr_api_JNI.h(通过在 mgr_api_JNI.java 上使用 javac -h 创建):

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_mgr_api_JNI */

#ifndef _Included_com_mgr_api_JNI
#define _Included_com_mgr_api_JNI
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_mgr_api_JNI
 * Method:    createInstance
 * Signature: (Lcom/mgr_api_types/EDisplayType;Ljava/lang/String;Lcom/mgr_api_types/ECommType;Ljava/lang/String;)V
 */
JNIEXPORT void JNICALL Java_com_mgr_1api_1JNI_createInstance
(JNIEnv *, jobject, jobject, jstring, jobject, jstring);

#ifdef __cplusplus
}
#endif
#endif

com_mgr_api_JNI.cpp:

#include "com_mgr_api_JNI.h"
static manager::CManagerApi* manager = NULL;

JNIEXPORT void JNICALL Java_com_mgr_1api_1JNI_createInstance(
                            JNIEnv *env,
                            jobject thisObj, 
                            jobject displayType,
                            jstring displaySerialNumber,
                            jobject commType,
                            jstring portName)
{
  manager::EDisplayType dType = convertObjectToDisplayType(env, displayType);
  const char* serialNumber = env->GetStringUTFChars(displaySerialNumber, 0);
  manager::ECommType comm = convertObjectToCommType(env, commType);
  const char* port = env->GetStringUTFChars(portName, 0);

  char buf[100];
  sprintf(buf,"%s",port);
  std::string portStr = buf;

  sprintf(buf,"%s",serialNumber);
  std::string serialNumStr = buf;

  if (manager == NULL)
  {
    manager = manager::CManagerApi::get();
    manager->initialize(dType, serialNumStr, comm, portStr);
  }

  // Release memory
  env->ReleaseStringUTFChars(displaySerialNumber, serialNumber);
  env->ReleaseStringUTFChars(portName, port);
}

Java代码的命令行执行:

java -cp /mnt/c/Workspace/library/java/:.:/home/fred/.local/share/py4j/py4j0.10.7.jar -Djava.library.path=/mnt/c/Workspace/build/library/ testsJNI

执行-XshowSettings:properties 会显示以下属性:

awt.toolkit = sun.awt.X11.XToolkit
file.encoding = UTF-8
file.separator = /
java.awt.graphicsenv = sun.awt.X11GraphicsEnvironment
java.awt.printerjob = sun.print.PSPrinterJob
java.class.path = /mnt/c/Workspace/library/java/
    .
    /home/fred/.local/share/py4j/py4j0.10.7.jar
java.class.version = 55.0
java.home = /usr/lib/jvm/java-11-openjdk-amd64
java.io.tmpdir = /tmp
java.library.path = /mnt/c/Workspace/build/library/

尝试解决问题

确保我有一个有效的原生库

在 java.library.path /mnt/c/Workspace/build/library/ 上执行 ls 会显示库 libMngr.so

如果我从该位置删除 libMngr.so,然后尝试运行 Java 会抱怨找不到库。

libMngr.so 执行nm 命令会显示以下内容:

000000000021f269 T Java_com_mgr_1api_1JNI_createInstance

所以Java可以找到本地库,并且它有函数的符号。

执行objdump 命令:

$objdump -f build/library/libMngr.so

build/library/libMngr.so:     file format elf64-x86-64
architecture: i386:x86-64, flags 0x00000150:
HAS_SYMS, DYNAMIC, D_PAGED
start address 0x000000000018aee0

显示本机库是 64 位的,根据 -XshowSettings:properties 我正在使用 64 位 Java。

我什至在mgr_api_JNI.java 中的System.loadLibrary("Mngr"); 之前放置了一个打印语句,以确保本机库只加载一次。

更新

我已从mgr_api_JNI.java 重新生成头文件并将函数声明复制到.cpp 文件以确保函数名称正确。但我仍然遇到同样的错误。

确保我有有效的 Java 类

如果我在 java.class.path /mnt/c/Workspace/library/java/ 上执行 ls,我会从编译 mgr_api_JNI.java 中找到所有 Java 类。

如果我删除类并尝试运行 Java,Java 会抱怨找不到类。

在 java.class.path /mnt/c/Workspace/library/java/ 上执行 grep -r createInstance 返回:

Binary file com/mgr_api_JNI.class matches
com/mgr_api_JNI.java: public native void createInstance(com.mgr_api_types.EDisplayType displayType,

所以Java可以找到编译后的Java类,它里面有createInstance方法。

问题

在我看来,Java 可以找到所有需要的类和本机库,但我仍然收到 UnsatisfiedLinkError 错误。

为什么我仍然收到此错误?

我需要做些什么来帮助 Java 找到/识别createInstance 方法?

【问题讨论】:

  • @Elliot Frisch 我认为这不正确。我读过的所有内容都表明java.library.path 就像 Linux 中的LD_LIBRARY_PATH。它只是提供了一个目录列表供 Java 搜索以查找库。另外,如果我必须指定库,那么 Java 会返回一个错误,告诉我找不到库。
  • 您也在加载Mngr,但有一个名为libMgr.so 的库文件,不确定是否只是问题中的拼写错误...
  • 是的,这是我的错字。真的是libMngr.so

标签: java java-native-interface unsatisfiedlinkerror


【解决方案1】:

这是你的错误

你有库文件:/mnt/c/Workspace/build/library/libMgr.so,但你在代码中加载了这个文件:System.loadLibrary("Mngr"); - 你有一个错字

您可以确保在名称正确的情况下它按预期工作

当您“离开”初始 JVM 时,-Djava.library.path 不再是向其他 JVM 提供信息的有效位置。我不知道py4j.GatewayConnection 的详细信息,但最好确保你没有运行另一个JVM 实例,或者你不在那里使用JNI

我建议进行以下测试:

  • LD_LIBRARY_PATH 设置为您的库所在的位置

  • 确保您可以仅使用 public class mgr_api_JNI 访问代码中的库(没有 Python 桥接引擎)

  • 如果您的第二个 JVM 有可能正在加载本机代码(但找不到它),请尝试使用 _JAVA_OPTIONS=-Djava.library.path=[path to library]。这样,所有JVMs 都会“看到”该位置 - 但您应该这样做只是为了测试目的

从另一个进程加载库看起来肯定有问题。如果我将您的代码简化为以下内容:

.
|-- Makefile
|-- README.md
|-- c
|   `-- com_mgr_api_JNI.cc
|-- java
|   `-- com
|       |-- mgr_api_JNI.java
|       `-- mgr_api_types
|           |-- ECommType.java
|           `-- EDisplayType.java
|-- lib
`-- target

以及代码本身

com_mgr_api_JNI.cc

#include <iostream>
#include "jni.h"
#include "com_mgr_api_JNI.h"

using namespace std;

JNIEXPORT void JNICALL Java_com_mgr_1api_1JNI_createInstance
  (JNIEnv *env, jobject cls, jobject a, jstring b, jobject c, jstring d) {
  cout << "Hello";
}

java/com/mgr_api_JNI.java

package com;
import com.mgr_api_types.*;

public class mgr_api_JNI
{
  static {
    try {
      System.loadLibrary("Mngr"); // Use "-Djava.library.path=[path to library]" option to load this library
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library 'Mngr' failed to load.\n" + e);
    }
  }

  public native void createInstance(  com.mgr_api_types.EDisplayType displayType,
                                      String displaySerialNumber,
                                      com.mgr_api_types.ECommType commType,
                                      String portName);

  public static void main(String [] arg) {

    mgr_api_JNI obj = new mgr_api_JNI();
    obj.createInstance(new com.mgr_api_types.EDisplayType(), "", new com.mgr_api_types.ECommType(), "");

  }
}

java/com/mgr_api_types/ECommType.java

package com.mgr_api_types;

public class ECommType { }

cat java/com/mgr_api_types/EDisplayType.java

package com.mgr_api_types;

public class EDisplayType { }

然后我构建代码

Makefile.common

ARCH=$(shell uname -s | tr '[:upper:]' '[:lower:]')
ifeq ($(ARCH),darwin)
  EXT=dylib
else
  EXT=so
endif

生成文件

include Makefile.common

all: compilejava compilec

compilec:
    c++ -std=c++11 -g -shared -fpic -I${JAVA_HOME}/include -I${JAVA_HOME}/include/$(ARCH) c/com_mgr_api_JNI.cc -o lib/libMngr.$(EXT)

compilejava:
    $(JAVA_HOME)/bin/javac -h c -d target -cp target java/com/mgr_api_types/EDisplayType.java
    $(JAVA_HOME)/bin/javac -h c -d target -cp target java/com/mgr_api_types/ECommType.java
    $(JAVA_HOME)/bin/javac -h c -d target -cp target java/com/mgr_api_JNI.java

test:
    $(JAVA_HOME)/bin/java -Djava.library.path=$(LD_LIBRARY_PATH):./lib -cp target com.mgr_api_JNI

clean:
    -rm -rfv target/*
    -rm c/*.h
    -rm -rf lib/*

它按预期工作

make test
/Library/Java/JavaVirtualMachines/jdk-12.0.1.jdk/Contents/Home/bin/java -Djava.library.path=:./lib -cp target com.mgr_api_JNI
Hello

我认为你的类被从另一个 JVM 实例调用,或者从通过 JNI 调用的东西调用,或者从另一个进程调用,而你的 -Djava.library.path 消失了。

另外,请尝试使用System.load("full/path/of/library.so") 以确保您可以从JVM 访问该库。

【讨论】:

  • libMgr.so 打错了,真的是libMngr.so。但我会考虑你的建议。
  • 原来是一个问题,我有另一个 JVM 实例仍在运行但没有死。一旦我杀死它,错误就消失了。
  • @Fred - 很高兴知道这可能会在这种特殊情况下导致错误。我很确定我会在某种程度上调查 py4j :)
【解决方案2】:

当运行时无法加载共享库中对应的native函数时会出现问题。

因此,在这些情况下,最好重新生成头文件以查看函数名称是否正确。

在这种情况下,您的函数名称看起来很可疑

Java_com_1mgr_1api_1JNI_createInstance

生成的名称使用_1 对Java 类/函数名称中的文字下划线进行编码。所以,根据类名mgr_api_JNI,名字应该是

Java_com_mgr_1api_1JNI_createInstance

相反。即第一个_1只是一个简单的下划线_,这也是我在为具有该名称的类生成头文件时看到的。

【讨论】:

  • 抱歉,我的帖子或代码中没有看到Java_com_mgr_1api_1JNI_createInstance(缺少_1)。
  • 是的,我已经重新生成了头文件,然后将函数声明复制到.cpp文件中。
  • @Fred 是的,它不在您的帖子中,这就是问题所在。即包名和函数名之间多余的_1不正确,应该只是一个下划线_
  • 明白。我会调查的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多