관리 메뉴

드럼치는 프로그래머

[JNI/NDK] Java의 String 을 JNI에서 다루는 예 본문

★─Programing/☆─JNI | NDK

[JNI/NDK] Java의 String 을 JNI에서 다루는 예

드럼치는한동이 2013. 4. 22. 09:24

JNI Functions Reference : http://download.oracle.com/javase/1.4.2/docs/guide/jni/spec/functions.html#wp17314

JNITest.java

public class JNITest
{
static{
System.loadLibrary("my_dll");
}

public native String greeting(String name);

public static void main(String[] args)
{
JNITest test = new JNITest();
String result = test.greeting("Smith");
System.out.println("C 함수 리턴값: "+result);
}
}



JNITest.h

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

#ifndef _Included_JNITest
#define _Included_JNITest
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: JNITest
* Method: greeting
* Signature: (Ljava/lang/String;)Ljava/lang/String;
*/

JNIEXPORT jstring JNICALL Java_JNITest_greeting
(JNIEnv *, jobject, jstring);

#ifdef __cplusplus
}
#endif
#endif





my_dll.c

#include <stdio.h>
#include "JNITest.h"
#include <string.h>

JNIEXPORT jstring JNICALL Java_JNITest_greeting
(JNIEnv *env, jobject obj, jstring jstr) {

const char *name = (*env)->GetStringUTFChars(env, jstr, NULL);//Java String to C Style string
char msg[60] = "Hello ";
jstring result;

strcat(msg, name);
(*env)->ReleaseStringUTFChars(env, jstr, name);
puts(msg);

result = (*env)->NewStringUTF(env, msg); // C style string to Java String
return result;

}


 

 

[출처] http://micropilot.tistory.com/category/J%20N%20I?page=3

Comments