我第一次尝试 native 方法......
我从这个链接Click进行了简单的编程。 ....
nativetest.java
public class nativetest
{
static {
System.loadLibrary("nativetest");
}
public native String sayHello(String s);
public static void main(String[] argv)
{
String retval = null;
nativetest nt = new nativetest();
retval = nt.sayHello("Beavis");
System.out.println("Invocation returned " + retval);
}
}
javac nativetest.java
javah -jni nativetest
已成功创建nativetest.h文件
nativetest.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class nativetest */
#ifndef _Included_nativetest
#define _Included_nativetest
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: nativetest
* Method: sayHello
* Signature: (Ljava/lang/String;)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_nativetest_sayHello(JNIEnv *, jobject, jstring);
#ifdef __cplusplus
}
#endif
#endif
nativetest.c代码
nativetest.c
include "nativetest.h" /*double quotes tells it to search current directory*/
JNIEXPORT jstring JNICALL Java_nativetest_sayHello (JNIEnv *env, jobject thisobject, jstring js)
{
return js;
}
gcc -I/usr/java/jdk1.7.0_13/include -I/usr/java/jdk1.7.0_13/include/linux -o nativetest.so -shared nativetest.c
已成功创建共享对象文件。
当我执行nativetest时,它显示以下错误
java -Djava.library.path=. nativetest
Exception in thread "main" java.lang.UnsatisfiedLinkError: no nativetest in java.library.path at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1860)
at java.lang.Runtime.loadLibrary0(Runtime.java:845)
at java.lang.System.loadLibrary(System.java:1084)
at nativetest.(nativetest.java:4)
提前致谢......
最佳答案
在 Linux 上,共享库的文件名应以“lib”开头,即“lib[library_name].so”。
引用:3.1.1. Shared Library Names
每个共享库都有一个特殊的名称,称为“soname”。 soname 具有前缀“lib”、库的名称、短语“.so”,后跟一个句点和一个版本号,该版本号在接口(interface)更改时递增(作为一个特殊异常(exception),最低级别的 C 库不以“lib”开头)。完全限定的 soname 包含其所在目录作为前缀;在工作系统上,完全限定的 soname 只是共享库“真实名称”的符号链接(symbolic link)。
关于java - native 方法链接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15516026/