gpt4 book ai didi

c - 使用同时加载另一个共享库的 JNI 加载动态 C 共享库

转载 作者:IT王子 更新时间:2023-10-29 00:38:50 26 4
gpt4 key购买 nike

在 Java eclipse (Linux) 上使用 JNI,我正在加载一个名为 first.so 的动态共享库。到目前为止一切顺利。问题在于,first.so 还会加载名为 second.so 的动态库。

运行程序时,我收到许多关于位于 second.so 中的符号的“ undefined symbol ”错误。

似乎使用 JNI 加载的库无法在运行时加载其他 C 库,因为我们处于 Java 环境中。我的假设正确吗?我是否需要特殊的编译标志来编译 first.so 库,或者是否需要特殊的参数来告诉 eclipse 它将在运行时加载 .so?

提前致谢!

最佳答案

It seems that a library loaded using JNI cannot load other C libraries on run-time because we are in a Java environment. Is my assumption correct?

没有。

libfirst.so 如何使用libsecond.so?是链接依赖,还是被dlopen加载?

我发现是这样的:

static {
System.loadLibrary("second");
System.loadLibrary("first");
}

通常在使用 JNI 的类中工作。

编辑:现在我知道你是如何加载 libsecond.so 这对我有用:

测试.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.solibsecond.so 没有链接在一起。

关于c - 使用同时加载另一个共享库的 JNI 加载动态 C 共享库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21618173/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com