在我的java代码中,我需要调用.dll库中存在的方法
我对此进行了很多尝试,使用 jna 以及使用 System.loadLIbraray()。 首先我创建了我的java,如下所示,编译后我使用javah生成了头文件Abc.h。
我将 Abc.h 放置在我的 Visual Studio 项目中并创建了一个 cpp 文件 然后我构建创建 .dll 文件的项目
public class Abc {
public native void greetings();
static {
System.loadLibrary("ClassLibrary1");
System.out.println("library loaded");
}
public static void main(String args[])
{ Abc abc = new Abc();
abc.greetings();
}
}
Abc.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class Abc */
#ifndef _Included_Abc
#define _Included_Abc
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT void JNICALL Java_Abc_greetings (JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
Abc.cpp
#include "Abc.h"
#include <stdio.h>
JNIEXPORT void JNICALL Java_Abc_greetings(JNIEnv *env,jobject jobj) {
printf("Hello from Visual C++!");
}
当我运行java程序时,它给出错误
java.lang.UnsatisfiedLinkError: Abc.greetings()V
请帮我解决这个问题
最佳答案
我有点困惑。 printf
调用是您自己编辑的吗?因为 JNI 样板代码是自动生成的,所以它不应该在那里。 JNI 正在通过接口(interface)查找它无法找到的已知函数 greetings()
。因此异常(exception)。此函数需要存在于 C++ 库中的某个位置。
这就是 JNI 样板代码的样子:
通过 Java 调用的 native 函数:
public static void helloWorldJNI()
{
helloWorld();
}
private static native void helloWorld();
对应的原生代码.h/.cpp:
static void helloWorld();
void somenamespace::UtilitiesNative::helloWorld()
{
LOG_DEBUG << "[JNI HELLO WORLD]";
}
自动生成的 JNI 样板文件,您无需编辑此内容:
JNIEXPORT void JNICALL Java_data_jni_UtilitiesNative_helloWorld(JNIEnv* env, jclass cls) {
jthrowable exc = NULL;
try {
somenamespace::UtilitiesNative::helloWorld();
} catch (...) {
exc = JavaCPP_handleException(env, 19);
}
if (exc != NULL) {
env->Throw(exc);
}
}
注意,后者不是我自己写的,而是JNI生成的。另请注意,它会检查数据,然后从自动生成的方法访问 helloWorld()
。
关于java.lang.UnsatisfiedLinkError : Abc. 问候语()V,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57377317/