我正在制作一个小应用程序来测试使用 jna 将本机库(linux 和 windows)集成到 java 代码中。
为此,我只需在库中调用一个方法并使用简单的 junit 测试检查结果。
问题在于,当第一个测试退出库时,它突然退出。
这是我使用的(简化的)代码:
interface NativeLibraryInterface extends Library {
static final String LIB_NAME_WINDOWS = "mylibW";
static final String LIB_NAME_LINUX = "mylibL";
NativeLibraryInterface INSTANCE = Native.load(Platform.isWindows() ? LIB_NAME_WINDOWS : LIB_NAME_LINUX, NativeLibraryInterface.class);
int func1(int argc, String[] argv) throws LastErrorException;
}
public interface INativeLibraryApi {
int myFunc1(String... args) throws LastErrorException;
}
public class NativeLibraryApi implements INativeLibraryApi {
@Override
public int myFunc1(String... args) throws LastErrorException {
try {
return NativeLibraryInterface.INSTANCE.func1(args.length, args);
} catch (LastErrorException e) {
System.out.println(e.getLocalizedMessage());
return -1;
} finally {
System.out.println("EXIT");
}
}
}
final class NativeLibraryTest {
static INativeLibraryApi nativeApi;
@BeforeAll
static void setup() {
nativeApi = new NativeLibraryApi();
}
@Test
void test1() throws Exception {
int result = nativeApi.myFunc1("myArgA", "myArgB");
assertEquals(0, result);
}
@Test
void test2() throws Exception {
int result = nativeApi.myFunc1("myArgC", "myArgD", "myArgE");
assertEquals(0, result);
}
}
当我单独运行每个测试或在整个测试类上运行 junit 时,func1 在控制台中显示预期的数据,因此我知道它已正确执行。但总是在退出对库的调用后就退出。
“EXIT”未显示,因此我认为执行在调用
NativeLibraryInterface.INSTANCE.func1(args.length, args);
期间或之后停止
我在这里做错了什么? 感谢您的帮助。
编辑1:
我做了一个测试,用系统库(libc.so)替换了我的本机库并调用了该方法
double cosh(double)
(我以此为例:https://www.baeldung.com/java-jna-动态库)并且它与 junit 完美配合,甚至在同一个测试中调用该函数几次也有效。所以我的图书馆肯定有问题,但我不明白它是什么。
编辑2:
我想我应该为库添加 C++ 代码(也经过简化):
编译选项:-g -ansi -pedantic -Wall -Wextra -m64 -O0
链接选项:-共享
myLibrary.hpp:
class MyLibrary {
public:
MyLibrary ();
~MyLibrary ();
int myFunc1 (
int argc,
char* argv[]
);
};
extern "C" int func1 (int argc, char* argv[]);
myLibrary.cpp:
#include "myLibrary.hpp"
MyLibrary::MyLibrary ()
{
}
MyLibrary::~MyLibrary ()
{
}
int MyLibrary::myFunc1 (int argc, char* argv[])
{
std::cout << "welcome" << std::endl;
exit (EXIT_SUCCESS);
}
extern "C" int func1(int argc, char* argv[])
{
MyLibrary library;
return library.myFunc1(argc, argv);
}
我找到了问题和解决方案:不要在代码中的任何地方使用
exit
-> 使用 return
。
说明:某些函数使用了
exit
,因为最初该库的代码是可执行文件的一部分。我刚刚删除了主要内容(+一些其他调整)以将其转换为库。
所以现在它可以完美运行了。