Java Native Interface 예제

author : Yoon Kyung Koo(yoonforh@yahoo.com)
Copyright (c) 1999 Yoon Kyung Koo, All rights reserved.

자바에서 c나 c++로 작성된 네이티브 라이브러리 함수를 호출하기 위해서는
자바 네이티브 인터페이스(JNI)를 사용해야 합니다.
다음은 윈도우 (WIN32) 시스템의 메모리 사용량을 검사하는 API 함수를 자바에서 사용하는 예제입니다.

사용되는 파일

JNI 구현 순서

  1. 먼저 자바 소스 파일을 작성합니다. MemoryStatus.java 파일에 보면 native로 선언된 메소드들이 있습니다. 이 메소드들은 C 라이브러리에서 구현됩니다.
  2. 자바 소스를 컴파일합니다.
    javac MemoryStatus.java
  3. JNI 스타일의 헤더 파일을 생성합니다.
    javah -jni MemoryStatus
    만들어진 헤더 파일은 MemoryStatus.h라는 이름을 가집니다.
  4. JNI 스타일 헤더 파일을 인클루드하는 실제 구현 라이브러리를 작성합니다. 여기에서는 WinMemory.c가 자바의 네이티브 메소드들을 구현하고 있습니다.
  5. 윈도우의 네이티브 라이브러리를 컴파일합니다. 적당한 Makefile을 만들어 사용하는 것이 편리합니다.
    Makefile 없이 도스 창에서 바로 컴파일하려면
    set JAVA_HOME=C:\jdk1.2 (JDK가 설치된 디렉토리)
    cl -I%JAVA_HOME%\include -I%JAVA_HOME%\include\win32 -LD WinMemory.c -Fewinmem.dll
    와 같이 직접 명령을 주면 됩니다.
  6. 참고로 작성된 winmem.dll 파일을 자바 가상 머신이 읽어들이는 것은 MemoryStatus.java 소스 코드에 있는 System.loadLibrary("winmem"); 루틴입니다.

The order of JNI implementation

  1. First, compose a Java source file, MemoryStatus.java. In that file, you can see methods declared as native. Those methods will be implemented in a C library.
  2. compile the Java code.
    javac MemoryStatus.java
  3. generate JNI header file.
    javah -jni MemoryStatus
    The generated header file will have the name of MemoryStatus.h.
  4. Compose the real implementation library which includes above generated header file. In this case, WinMemory.c implements Java's native methods.
  5. Compile native library. A simple Makefile will help you.
    If you want to compile in dos prompt without Makefile, then do as follows.
    set JAVA_HOME=C:\jdk1.2 (the directory where JDK locates)
    cl -I%JAVA_HOME%\include -I%JAVA_HOME%\include\win32 -LD WinMemory.c -Fewinmem.dll
  6. for your information, where Java Virtual Machine loads winmem.dll is the routine System.loadLibrary("winmem") in MemoryStatus.java.

이 페이지는 1999년 2월 22일에 처음 만들어졌습니다.
튜토리얼 페이지로 돌아가기