1. Native Method를 선언하는 자바 클래스를 작성한다.
  2. 1.에서 작성한 자바 클래스를 컴파일 한다.
  3. Native Method가 사용할 헤더 파일을 생성한다.
  4. C/C++언어로 Native Method를 구현한다.                                                                    (3.에서 생성한 헤더 파일을 Visual Studio 프로젝트에 추가)
  5. 헤더 파일과 구현 파일을 컴파일한다.
  6. 자바 프로그램을 실행한다.

(자바 컴파일은 도스 창에서 javac 명령어를 이용하여 컴파일한다.
 이클립스를 이용하는 예제는 다음에 추가하겠음.)

1. Native Method를 선언하는 자바 클래스를 작성

아주 아주 간단한 test class를 만들었다.
* 여기에서 사용하는 dll의 이름은 "Hello_DLL"이다. 운영체제가 윈도우면 Hello_DLL.dll 을 사용하면 되고 리눅스면 Hello_DLL.so를 사용한다.

import java.util.*;

class test {

   native void HelloMethod();

   static {

  System.loadLibrary("Hello_DLL");

   }

   public static void main(String args[]) {   

      test test = new test();

      test.HelloMethod();

   }

}



2. test.java 를 컴파일

도스 창에서 컴파일 한다.

C:\>javac test.java

test.class 파일이 생성된다.


3. Native Method가 사용할 헤더 파일 생성

도스 창에서 javah 명령어를 사용하여 헤더 파일을 생성한다.
* 사용법 : javah "class 파일 이름"

C:\>javah test

test.h 파일이 생성된다.

#include <jni.h>

#ifdef __cplusplus

extern "C" {

#endif

/*

 * Class:     test

 * Method:    HelloMethod

 * Signature: ()V

 */

JNIEXPORT void JNICALL Java_test_HelloMethod (JNIEnv *, jobject);

#ifdef __cplusplus

}

#endif

#endif



4. C언어로 Native Method 실제 구현

* Visual Studio project 설정
- dll용 프로젝트로 생성한다 -> Win32 Dynamic-Link Library
- 프로젝트에 test.h 파일을 추가한다.

간단하게 도스 화면에 " Hello Jni~! from C++ "을 출력하는 함수를 구현했다.

hello_Dll.cpp

#include <jni.h>

#include <stdio.h>

#include "test.h"

JNIEXPORT void JNICALL Java_test_HelloMethod (JNIEnv *env, jobject obj){

     printf("Hello Jni~! from C++");

}



5. C 코드와 헤더 파일을 컴파일

그 결과로 hello_DLL.dll이 생성된다.
프로젝트 세팅에서 test.class파일이 들어있는 폴더로 output 위치를 변경할 수 있고 dll을 복사해서 test.class가 있는 폴더로 넣는다.
(이 때는 간단하기 때문에 복사해도 되지만 되도록 output위치를 변경하자.)


6.자바 프로그램 실행

test.class 파일을 실행시킨다.

사용자 삽입 이미지