我在CS课程简介的最后一个项目中使用JNI。我几乎可以让它发挥作用,但上周末我犯了一个错误。我到处找了很多地方,但都没能修好。
我得到的错误:java.lang.UnsisfiedLinkError:JNI_Functions.dllHello()V
我的代码:
////////////////////////
// JNI_Functions.c
#include "JNI_Functions.h"
#include <jni.h>
#include <stdio.h>
JNIEXPORT void JNICALL Java_JNI_1Functions_dllHello(JNIEnv *env, jobject obj) {
printf("This was sent from the DLLn");
return;
}
///////////////////////
// JNI_Functions.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class JNI_Functions */
#ifndef _Included_JNI_Functions
#define _Included_JNI_Functions
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: JNI_Functions
* Method: dllHello
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_JNI_1Functions_dllHello
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
//////////////////// JAVA ///////////////////
// Entry.java
public class Entry {
public static void main(String[] args) {
try {
// JNI_Functions jni = new JNI_Functions();
// jni.dllHello();
new JNI_Functions().dllHello();
} catch (UnsatisfiedLinkError e) {
System.out.println("Couldn't call native function.n" + e);
}
}
}
///////////////////////
// JNI_Functions.java
public class JNI_Functions {
public JNI_Functions() {
System.loadLibrary("JNI_Functions");
System.out.println("Loaded JNI_Functions.dll");
}
// Prints out a simple hello world from the dll
public native void dllHello();
}
我正在使用Code::Blocks进行编译,如果需要,这里有输出:
-------------- Build: Release in JNI_Functions (compiler: GNU GCC Compiler)---------------
mingw32-gcc.exe -Wall -O2 -D_JNI_IMPLEMENTATION_ -Wl,--kill-at -ID:JNITest -c D:JNI_FunctionsJNI_Functions.c -o objReleaseJNI_Functions.o
mingw32-g++.exe -shared -Wl,--output-def=binReleaselibJNI_Functions.def -Wl,--out-implib=binReleaselibJNI_Functions.a -Wl,--dll objReleaseJNI_Functions.o -o binReleaseJNI_Functions.dll -s
Output file is binReleaseJNI_Functions.dll with size 9.00 KB
Process terminated with status 0 (0 minute(s), 9 second(s))
0 error(s), 0 warning(s) (0 minute(s), 9 second(s))
如果类或方法名称包含下划线,则它在C中变为_1
,而不是_
。这使得JNI_Functions.method
和JNI.Functions_method
不具有相同的C名称。
参见中的表2-1http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/design.html.
在您的情况下,C函数应该被称为Java_JNI_1Functions_dllHello
。