Java Reference
In-Depth Information
Example 5.8
Header file for
GetUser
native methods (
GetUser.h
)
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class GetUser */
#ifndef _Included_GetUser
#define _Included_GetUser
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: GetUser
* Method: getUserName
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_GetUser_getUserName
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
Example 5.9
Native method's C implementation file (
GetUser.c
)
#include "GetUser.h"
#include <stdio.h>
JNIEXPORT jstring JNICALL
Java_GetUser_getUserName(JNIEnv *jenv, jobject obj)
{
char buffer[L_cuserid + 1];
cuserid(buffer);
return (*jenv)->NewStringUTF(jenv, buffer);
}
All of the Java class member data and Java class methods may be reached
through the
JNIEnv
pointer argument. There are also methods provided by
JNI itself. One of those is
NewStringUTF()
. Remember that Java
String
s are
Unicode, not 8-bit ASCII, so you must convert to and from Unicode (UTF-8