状态描述    我想采用在java中调用本地C代码,用动态链接库的方式(其他方式我还不知道有没有)就是先编写java类的native方法,之后用javah -jni命令生成.h文件。之后利用VC制作动态链接库dll,我现在在windows下尝试。
问题        现在的问题是我在java中能够加载dll文件,但是在执行本地方法的时候却不能执行,UnsatisfiedLinkError,文档中描述是找不到本地方法才抛出的异常,但是我是按照.h中的函数声明来定义的函数,请高手说说可能存在哪些错误,制作Dll要注意什么情况。多谢了!!!

解决方案 »

  1.   

    1. 你是怎么判定“能够加载dll文件”的?2. 你的 DLL 有没有把实现 native 方法的那个函数做 EXPORT ?EXPORT 出来的名字是不是 _Java_yourpackage_yourclass_yourmethod@nn 这种形式的?
      

  2.   

    学习,到这里看看,能不能查出错
    http://www.pconline.com.cn/pcedu/empolder/gj/java/0506/642328_2.html
      

  3.   

    http://gceclub.sun.com.cn/yuanchuang/week-15/jni.html
      

  4.   

    找不到你的dll吧, 可以在path环境变量里面加入 ".", 表示当前目录, 如果不这样, 也可写入完整的文件名, 包括路径. 如果还不行, 看看是否采用了System.loadLibrary方法, 试一试使用System.load的方法
      

  5.   

    加载成功了,没有抛出异常,但是如果加上本地方法的调用,就出错了。帮我看看,我把代码贴出来。头文件 /* DO NOT EDIT THIS FILE - it is machine generated */
    #include <jni.h>
    /* Header for class TestNative */#ifndef _Included_TestNative
    #define _Included_TestNative
    #ifdef __cplusplus
    extern "C" {
    #endif
    /*
     * Class:     TestNative
     * Method:    set
     * Signature: ()V
     */
    JNIEXPORT void JNICALL Java_TestNative_set
      (JNIEnv *, jobject);#ifdef __cplusplus
    }
    #endif
    #endif实现文件 
    // Dll.cpp : Defines the entry point for the DLL application.
    //#include "stdafx.h"
    #include "Dll.h"#include "TestNative.h"BOOL APIENTRY DllMain( HANDLE hModule, 
                           DWORD  ul_reason_for_call, 
                           LPVOID lpReserved
     )
    {
        switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
    break;
        }
        return TRUE;
    }
    // This is an example of an exported variable
    DLL_API int nDll=0;// This is an example of an exported function.
    DLL_API int fnDll(void)
    {
    return 42;
    }// This is the constructor of a class that has been exported.
    // see Dll.h for the class definition
    CDll::CDll()

    return; 
    }
    extern "C" JNIEXPORT void JNICALL Java_TestNative_set
    (JNIEnv *, jobject){
    //do some thing
    }
    java部分package dlmse.training;public class TestNative {
    static {
    System.loadLibrary("DllTest");
    } public static void main(String args[]) {
    System.out.println("a successful invoke!");
    TestNative t = new TestNative();
    t.set();
    } public native void set();
    }
      

  6.   

    我看到例子中的头文件生成的方法名称包含包路径,是不是我的没有,在这里出错的。但是是javah -jni命令生成出来的。应该不会有错的!
      

  7.   

    你的 Java 程序是 dlmse.training.TestNative
    那么,你的 C 程序应该是
        JNIEXPORT void JNICALL Java_dlmse_training_TestNative_set
    而你现在的程序是
        JNIEXPORT void JNICALL Java_TestNative_set
      

  8.   

    估计是因为你在用 javah 的时候,TestNative.class 是在“当前路径”下,而不是在 .\dlmse\training 路径下。class 文件应该在 .\dlmse\training 路径下。