jni String to * char和java.lang.UnsatisfiedLinkError:

时间:2013-11-13 00:28:20

标签: java c++ java-native-interface

我试图用JNI运行简单的程序,在我尝试使用Strings之前,一切都运行良好:

hello.java:

public class hello {
  public native String getLine(String name) ;
  public static void main (String args[]) {
    String str = "Pawel" ;
    hello h = new hello () ;
    System.out.println(h.getLine(str)) ;
  }
  static {
    System.loadLibrary ( "hello" ) ;
  }
}

的hello.c:

#include<stdio.h>
#include<jni.h>
#include "hello.h" 

JNIEXPORT jstring JNICALL 
Java_Prompt_getLine(JNIEnv *env, jobject obj, jstring prompt)
 {
   char buf[128];
   const jbyte *str;
   str = (*env)->GetStringUTFChars(env, prompt, NULL);
   if (str == NULL) {
       return NULL; 
   }
   printf("%s", str);
   (*env)->ReleaseStringUTFChars(env, prompt, str);
   scanf("%s", buf);
   return (*env)->NewStringUTF(env, buf);
 }

hello.h:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class hello */

#ifndef _Included_hello
#define _Included_hello
#ifdef __cplusplus
extern "C" {
#endif

JNIEXPORT jstring JNICALL Java_hello_getLine
(JNIEnv *, jobject, jstring);

#ifdef __cplusplus
}
#endif
#endif

我正在编译:

gcc -fPIC -I /usr/lib/jvm/java-7-openjdk-amd64/include -I /usr/lib/jvm/java-7-openjdk-amd64/include/linux -shared -o libhello.so hello.c

并以:

运行
java -Djava.library.path=. hello

输出:

Exception in thread "main" java.lang.UnsatisfiedLinkError: hello.getLine(Ljava/lang/String;)Ljava/lang/String;
    at hello.getLine(Native Method)
    at hello.main(hello.java:9) //it points to native function call

怎么了?

1 个答案:

答案 0 :(得分:1)

Java_Prompt_getLine功能重命名为Java_hello_getLine

中的hello.c