我正在尝试从 C++ 调用 Java 中的简单本机方法,为此我执行以下操作:
创建一个简单的类,如下所示:
public class HelloNative{ public native void printString(String str); static{ System.out.println("Current Directory is: " + System.getProperty("user.dir")); System.load(System.getProperty("user.dir") + "/libhellonative.so"); } public static void main(String[] args){ System.out.println("Calling Native Libraray (libhellonative.so) method printString"); new HelloNative().printString("Message from Java to C"); } }
为本地方法创建 .h 文件,使用
javah -jni
该文件创建以下声明:JNIEXPORT void JNICALL Java_HelloNative_printString(JNIEnv *, jobject, jstring);
将文件中的本机函数实现
.cpp
为:JNIEXPORT void JNICALL Java_HelloNative_printString(JNIEnv* jni_env, jobject java_obj, jstring msg){ printf("inside native method\n"); jboolean iscopy; const char *message = (jni_env)->GetStringUTFChars( msg, &iscopy); printf("%s", message); }
最后
.so
使用以下命令创建文件:g++ HelloNative.cpp -o libhellonative.so -shared -Wl,-soname,libhellonative.so -static -lc -I /usr/lib/jvm/java-6-sun-1.6.0.26/include -I /usr/lib/jvm/java-6-sun-1.6.0.26/include/linux
但是当我编译并运行 .java 文件时,它给了我运行时异常:
Current Directory is: /home/gmuhammad/Projects/test
Calling Native Libraray (libhellonative.so) method printString
Exception in thread "main" java.lang.UnsatisfiedLinkError: HelloNative.printString(Ljava/lang/String;)V
at HelloNative.printString(Native Method)
at HelloNative.main(HelloNative.java:16)