似乎使用 JNI 加载的库无法在运行时加载其他 C 库,因为我们处于 Java 环境中。我的假设正确吗?
没有。
libfirst.so 如何使用libsecond.so?是链接依赖,还是dlopen加载的?
我发现了类似的东西:
static {
System.loadLibrary("second");
System.loadLibrary("first");
}
在使用 JNI 的类中通常可以工作。
编辑:现在我知道你是如何加载 libsecond.so 这对我有用:
Test.java
public class Test {
public static void main (String args[]) {
test();
}
private native static void test();
static {
System.loadLibrary("first");
}
}
first.c -- libfirst.so的唯一翻译单元
#include <jni.h>
#include "Test.h"
#include <dlfcn.h>
#define LIBNAME "libsecond.so"
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: Test
* Method: test
* Signature: ()V
*/
JNIEXPORT void JNICALL
Java_Test_test(JNIEnv *env , jclass cls)
{
void* h;
void (*sym)(void);
h = dlopen(LIBNAME, RTLD_LAZY|RTLD_GLOBAL);
if (h) {
printf("dlopen " LIBNAME " worked\n");
sym = (void (*)(void))dlsym(h,"second");
sym();
} else {
printf("dlopen " LIBNAME " failed\n");
}
}
#ifdef __cplusplus
}
#endif
second.c -- libsecond.so的唯一翻译单元
#include <stdio.h>
void
second(void)
{
printf("hello from second\n");
}
生成文件
CFLAGS=-fPIC
all : libfirst.so libsecond.so
libsecond.so : second.o
$(CC) -shared -Wl,-soname,libsecond.so.0 -o $@ $^ -lc
libfirst.so : first.o
$(CC) -shared -Wl,-soname,libfirst.so.0 -o $@ $^ -ldl -lc
clean:
rm -f *.o *.so
Test.h 可以由javah Test 生成。请注意,libfirst.so 和 libsecond.so 没有链接在一起。