如何使用 g++ 在 Windows 平台中为 JNI 生成 dll 时修复不满意的链接错误



我是原生编程的新手。我一直在尝试修复过去 8-9 小时的不满意链接错误,但没有得到任何结果。经过大量的谷歌搜索和堆栈溢出,我厌倦了修复它,我在这里发布我的问题。有人请帮助我。我在 Windows 32 位环境中使用 g++ 编译器。以下是我创建的文件:

演示.java

class Demo 
{
    // Declaration of the native method
    public native int methodOfC(int arg1);
    /*The native keyword tells the compiler that the implementation of this method is in a native language*/
    /*Loading the library containing the implementation of the native method*/
    static 
    {
        System.out.println("Control is in Java.......going to call a C program......n");
        System.loadLibrary("try");
        System.out.println("Congr8s no prob in CallApi.....n");
    }
    public static void main(String[] args) 
    {
        //invoking the native method  
        int sendToC,getFrmC;
        if(args.length!=0) sendToC=Integer.parseInt(args[0]);
        else sendToC=999;
        Demo ob1=new Demo();
        getFrmC=ob1.methodOfC(sendToC);
        System.out.println("This is in Java......n Got "+ getFrmC +" in return from C.");
    }//end main
}//end Demo

演示.h

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class Demo */
#ifndef _Included_Demo
#define _Included_Demo
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     Demo
 * Method:    methodOfC
 * Signature: (I)I
 */
JNIEXPORT jint JNICALL Java_Demo_methodOfC
  (JNIEnv *, jobject, jint);
#ifdef __cplusplus
}
#endif
#endif

DemoImp.c

#include <jni.h>
#include "Demo.h"
#include <stdio.h>
//definition of methodOfC()
JNIEXPORT int JNICALL Java_Demo_methodOfC(JNIEnv* exeenv, jobject javaobj, int getFrmJava)
{
    printf("This is in the C programn Got %d from java",getFrmJava);
    printf("n.......Exiting frm Cn");
    return getFrmJava+1;
}

以下是我编译和运行程序的方式:屏幕截图在这里

C:native>javac Demo.java
C:native>javah -jni Demo
C:native>g++ -c  -l"C:Javajdk1.6.0_26include" -l"C:Javajdk1.6.0_26includewin32" DemoImp.c
C:native>g++ -shared DemoImp.o -o try.dll
C:native>java Demo 1234
Control is in Java.......going to call a C program......
Congr8s no prob in CallApi.....
Exception in thread "main" java.lang.UnsatisfiedLinkError: Demo.methodOfC(I)I
        at Demo.methodOfC(Native Method)
        at Demo.main(Demo.java:23)
C:native>

我已经在我的系统路径变量中添加了"C:ative"。我已经在mediafire中上传了我的所有文件。这是原生链接.zip如果可能,请告诉我如何制作 64 位版本的 dll。提前谢谢。

您错过了 DemoImp.c 文件中的软件包名称。

C 函数的命名约定是 Java_{package_and_classname}_{function_name}(JNI 参数)。包名称中的点应替换为下划线。

最新更新