목적 : C, C++ 과 연동 하기 위한 java interface
테스트 환경 - VM: jdk1.4
- C compiler : gcc
- Hello.java source
package test;
import java.io.*;
public class Hello
{
public native String helloworld(String name); // C 프로그램으로 부터 호출할 메소드명
static {
System.loadLibrary("hello");
}
public static void main(String args[])
{
Hello h = new Hello();
System.out.println(h.helloworld("파이 짱"));
}
} 컴파일 하기
[sun:/export/home/pioneer/jni/HelloJni]javac -d . Hello.java
c 와 interface 할 Header 파일 만들기
[sun:/export/home/pioneer/jni/HelloJni]javah -jni Hello
[sun:/export/home/pioneer/jni/HelloJni]ls *.h
NativeStringUtil.h - 한글처리를 위한 파일
test_Hello.h - Jni 를 위한 Header 파일 package명_클래스명
[sun:/export/home/pioneer/jni/HelloJni]
Header 파일
[sun:/export/home/pioneer/jni/HelloJni]more test_Hello.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class test_Hello */
#ifndef _Included_test_Hello
#define _Included_test_Hello
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: test_Hello
* Method: helloworld
* Signature: (Ljava/lang/String;)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_test_Hello_helloworld
(JNIEnv *, jobject, jstring);
#ifdef __cplusplus
}
#endif
#endif
C source hello.c 파일
#include <jni.h>
#include "test_Hello.h"
#include "NativeStringUtil.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
JNIEXPORT jstring JNICALL
Java_test_Hello_helloworld(JNIEnv *env, jobject obj, jstring str)
{
char buf[1024];
char *cstr;
cstr = jbyteArray2cstr( env, javaGetBytes(env, str) );
sprintf(buf, "%s:%s", cstr, "반가워요 이건 C함수에서 넘겨준 겁니다.");
return javaNewString( env, cstr2jbyteArray(env, buf));
}
C 파일 compile 하기
gcc -I/usr/j2se/include -I/usr/j2se/include/solaris -G -o libhello.so hello.c NativeStringUtil.c
실행하기
[sun:/export/home/pioneer/jni/HelloJni]java -Djava.library.path=./ test.Hello
반가워요 이건 C함수에서 넘겨준 겁니다.
[sun:/export/home/pioneer/jni/HelloJni]
|