首页 > 解决方案 > 将代码移动到包中后出现 UnsatisfiedLinkError

问题描述

我正在开发一个需要使用 .so 库(ubuntu 18.04)的项目,当我将我的 java 代码放在 /src 文件夹中时一切正常(我使用的是 IntelliJ Idea),但是在我将我的代码移动到一个命名的包(smutil),它会导致一些错误,例如“线程“主”java.lang.UnsatisfiedLinkError中的异常:smutil.GmSSL.digest(Ljava/lang/String;[B)[B”

这是我的代码

package smutil;
public class GmSSL {

public native String[] getVersions();
public native String[] getCiphers();
public native String[] getDigests();
public native String[] getMacs();
public native String[] getSignAlgorithms();
public native String[] getPublicKeyEncryptions();
public native String[] getDeriveKeyAlgorithms();
public native byte[] generateRandom(int length);
public native int getCipherIVLength(String cipher);
public native int getCipherKeyLength(String cipher);
public native int getCipherBlockSize(String cipher);
public native byte[] symmetricEncrypt(String cipher, byte[] in, byte[] key, byte[] iv);
public native byte[] symmetricDecrypt(String cipher, byte[] in, byte[] key, byte[] iv);
public native int getDigestLength(String digest);
public native int getDigestBlockSize(String digest);
public native byte[] digest(String algor, byte[] data);
public native String[] getMacLength(String algor);
public native byte[] mac(String algor, byte[] data, byte[] key);
public native byte[] sign(String algor, byte[] data, byte[] privateKey);
public native int verify(String algor, byte[] digest, byte[] signature, byte[] publicKey);
public native byte[] publicKeyEncrypt(String algor, byte[] in, byte[] publicKey);
public native byte[] publicKeyDecrypt(String algor, byte[] in, byte[] privateKey);
public native byte[] deriveKey(String algor, int keyLength, byte[] peerPublicKey, byte[] privateKey);
public native String[] getErrorStrings();

static {
    System.loadLibrary("gmssljni");
}
}

标签: javaintellij-ideajava-native-interfaceunsatisfiedlinkerror.so

解决方案


您可能将.so文件打包在 JAR 中。请注意,一旦你在.so那里,加载库就不是那么容易了。

为了加载共享库,您必须确保它在文件系统上。您可以通过将其提取到临时位置来解决此问题。

在此处查看说明此主题的完整示例:

https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo031

基本上,您需要做的是:

  • 在 JAR 中找到您的资源
  • 将其提取到临时位置
  • 用户System.load(fullPathToFile)

而已 :)

JNI 玩得开心!


推荐阅读