c - Java:对natie方法调用的UnsatisfiedLinkError

时间:2013-11-19 11:59:47

标签: java c eclipse java-native-interface eclipse-cdt

我正在研究JNI。 我创建了一个简单的java类:

package asd.jni;

public class PrintJNI {

  public native String print();

  static{
   try{
      System.out.println("loading libPrint");
      System.load("C:/DeLauri/WorkSpaceC_CPP/Print2/Debug/libPrint.dll");  
      System.out.println("libPrint loaded");
  }catch(UnsatisfiedLinkError e){
      System.out.println("error "+e.toString());
      e.printStackTrace();
  }
 }
}

手动调用javah -jni我创建了asd_jni_PrintJNI.h:

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

#ifndef _Included_asd_jni_PrintJNI
#define _Included_asd_jni_PrintJNI
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     asd_jni_PrintJNI
 * Method:    print
 * Signature: ()Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_asd_jni_PrintJNI_print
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

在Eclipse CDT中,我创建了一个名为&#34; Print&#34;在里面我创建一个Print.c:

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

JNIEXPORT jstring JNICALL Java_asd_jni_PrintJNI_print  (JNIEnv *env, jobject obj) {

printf("aasdasdadasd");
const char rtn[10]  = "Hello \n";

printf("aasdasdadasd");
return (*env)->NewStringUTF(env, rtn);
}

一切都编译成功,但是当我运行我的主类时:     包asd;

import asd.jni.PrintJNI;

public class StartPrintJNI {

/**
 * @param args
 */
public static void main(String[] args) {

    try{
        PrintJNI print = new PrintJNI();

        System.out.println("call");
        String cStrg = print.print();
        System.out.println("called");
        System.out.println(cStrg);
    }catch(UnsatisfiedLinkError e){
          System.out.println("error in main "+e.toString());
          e.printStackTrace();
      }catch(Exception e){
         System.out.println("2 "+ e.getMessage());
         e.printStackTrace();
     }

}

}

我有以下错误:

loading libPrint
libPrint loaded
call
error in main java.lang.UnsatisfiedLinkError: asd/jni/PrintJNI.print()Ljava/lang/String;
java.lang.UnsatisfiedLinkError: asd/jni/PrintJNI.print()Ljava/lang/String;
at asd.StartPrintJNI.main(StartPrintJNI.java:16)

有人能帮助我吗? 谢谢

更新:我在Eclipse / Eclipse CDT IDE中使用MinGW在Windows 7上进行这些测试

2 个答案:

答案 0 :(得分:0)

将DLL与MingW链接时,请使用

-Wl,--export-all-symbols -Wl,--add-stdcall-alias -m32 -shared

导出功能的非装饰副本。

请勿更改方法签名;你正在掩盖你的问题。

答案 1 :(得分:-1)

我解决了我的问题。我刚刚在“asd_jni_PrintJNI.h”中为方法定义添加了一个下划线“_”:

JNIEXPORT jstring JNICALL _Java_asd_jni_PrintJNI_print
(JNIEnv *, jobject)

因此在“Print.c”中更改方法的名称:

JNIEXPORT jstring JNICALL _Java_asd_jni_PrintJNI_print  (JNIEnv *env, jobject obj)