Eclipse Java JNI, ошибка связывания LoadLibrary - PullRequest
0 голосов
/ 27 января 2010

Это мой второй раз кодирующий Java и никогда не ссылающийся на какую-либо внешнюю библиотеку. Я следую за примерами JNI онлайн и получаю UnsatisfiedLinkError при попытке загрузить dll. Я думал, что прежде чем пытаться загрузить, я должен создать DLL, но во всех примерах, которые я посмотрел, они не упоминают о создании DLL. Большинство из них заявили, что я должен сначала создать код Java, а затем собственный код.

public class ClassSample1 
{
 public native void displayHelloWorld();

 static
 {
  System.loadLibrary("MyLittleJNI");

 } 


 public static void main(String[] args) 
 {
  // TODO Auto-generated method stub
  ClassSample1 classSample1;
  classSample1 = new ClassSample1();
  classSample1.displayHelloWorld();

  System.out.println("Hello");
 }

}

Как я могу получить ошибку?

Ответы [ 2 ]

1 голос
/ 27 января 2010

В приведенном вами примере кода предполагается, что в пути поиска есть DLL с именем MyLittleJNI.dll, содержащая метод displayHelloWorld. Фактическое имя функции C в DLL оформлено с использованием четко определенного синтаксиса.

Если вы получаете UnsatisfiedLinkError в loadLibrary (), это потому, что JVM не может найти DLL. Вы можете временно устранить проблему, указав полный путь к библиотеке DLL, используя вместо этого метод System.load(filename).

После успешного выполнения load или loadLibrary необходимо убедиться, что собственная функция названа правильно. Чтобы помочь в этом, вы можете использовать javah для генерации файла заголовка, содержащего прототипы для всех встроенных функций в классе.

Более подробную информацию о том, как использовать JNI, можно найти в здесь и здесь .

РЕДАКТИРОВАТЬ: Кроме того, столбец «Связанные» справа от этого вопроса, кажется, содержит несколько полезных связанных вопросов.

0 голосов
/ 28 января 2010

Я снова пытаюсь создать новый проект.

Итак, вот файл JNISample2.java

public class JNISample2
{

    static
    {
        System.loadLibrary("JNISample2Dll");        
    } 

    public native void displayHelloWorld();

    public static void main(String[] args) 
    {
        System.out.println("from java Hello");

        JNISample2 JNIsample2;
        JNIsample2 = new JNISample2();
        JNIsample2.displayHelloWorld();
    }

}

И здесь .h файл, который генерируется javah -classpath. JNISample2

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

#ifndef _Included_JNISample2
#define _Included_JNISample2
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     JNISample2
 * Method:    displayHelloWorld
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_JNISample2_displayHelloWorld
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

Вот мой DLL-файл .h, который я создаю VS2005 с приложением MFC.

// JNISample2Dll.h : main header file for the JNISample2Dll DLL
//

#pragma once

#ifndef __AFXWIN_H__
    #error "include 'stdafx.h' before including this file for PCH"
#endif

#include "resource.h"       // main symbols


#include "JNISample2.h"


// CJNISample2DllApp
// See JNISample2Dll.cpp for the implementation of this class
//

class CJNISample2DllApp : public CWinApp
{
public:
    CJNISample2DllApp();

// Overrides
public:
    virtual BOOL InitInstance();

    DECLARE_MESSAGE_MAP()
};


JNIEXPORT void JNICALL Java_JNISample2_displayHelloWorld(JNIEnv *, jobject);

А вот и мой .cpp файл

// JNISample2Dll.cpp : Defines the initialization routines for the DLL.
//

#include "stdafx.h"
#include "JNISample2Dll.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

//
//TODO: If this DLL is dynamically linked against the MFC DLLs,
//      any functions exported from this DLL which call into
//      MFC must have the AFX_MANAGE_STATE macro added at the
//      very beginning of the function.
//
//      For example:
//
//      extern "C" BOOL PASCAL EXPORT ExportedFunction()
//      {
//          AFX_MANAGE_STATE(AfxGetStaticModuleState());
//          // normal function body here
//      }
//
//      It is very important that this macro appear in each
//      function, prior to any calls into MFC.  This means that
//      it must appear as the first statement within the 
//      function, even before any object variable declarations
//      as their constructors may generate calls into the MFC
//      DLL.
//
//      Please see MFC Technical Notes 33 and 58 for additional
//      details.
//


// CJNISample2DllApp

BEGIN_MESSAGE_MAP(CJNISample2DllApp, CWinApp)
END_MESSAGE_MAP()


// CJNISample2DllApp construction

CJNISample2DllApp::CJNISample2DllApp()
{
    // TODO: add construction code here,
    // Place all significant initialization in InitInstance
}


// The one and only CJNISample2DllApp object

CJNISample2DllApp theApp;


// CJNISample2DllApp initialization

BOOL CJNISample2DllApp::InitInstance()
{
    CWinApp::InitInstance();

    return TRUE;
}


JNIEXPORT void JNICALL Java_JNISample2_displayHelloWorld(JNIEnv *, jobject)
{
    MessageBox(NULL, TEXT("In JNISample2Dll"), TEXT("DLL"), 1);
}

После того, как я запустил командную строку: java JNISample2, он отображает строку «из java Hello», но почему он не отображает окно сообщения, которое я помещаю в DLL-файл .cpp?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...