Handling strings in Java differs from handling strings in C. A string in Java is encoded in Unicode. Conversely, C uses the Universal Character Set (UCS) Transformation Format-8 (UTF-8) to represent strings. The native equivalent of a string in Java is jstring, which cannot be used as a string in C.
Accessing a Java String in C
class StringDemo
{
String str;
//Declaring a native method
private native void strDemo();
public static void main(String args[])
{
StringDemo dem = new StringDemo();
dem.str = "This is a string declared in Java";
//invoking the native method
dem.strDemo();
System.out.println("String in Java:\n");
System.out.println(" dem.str = \"" + dem.str + "\"");
}
static
{
//loading library
System.loadLibrary("StringDemo_lib");
}
}//end class
Header File for the StringDemo File
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class StringDemo */
#ifndef _Included_StringDemo
#define _Included_StringDemo
#ifdef __cplusplus
extern "C"
{
#endif
/*
* Class: StringDemo
* Method: strDemo
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_StringDemo_strDemo (JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
Implementation of the strDemo Method
#include <stdio.h>
#include <jni.h>
#include "StringDemo.h"
JNIEXPORT void JNICALL
Java_StringDemo_strDemo(JNIEnv *exeenv, jobject javaobj)
{
jclass cls = (*exeenv)->GetObjectClass(exeenv, javaobj);
jfieldID fid;
jstring jstring;
const char *string;
printf("String accessed in C\n");
fid = (*exeenv)->GetFieldID(exeenv, cls, "str", "Ljava/lang/String;");
if (fid == 0)
{
return;
}
jstring = (*exeenv)->GetObjectField(exeenv, javaobj, fid);
string = (*exeenv)->GetStringUTFChars(exeenv, jstring, 0);
printf("dem.s = \"%s\"\n", string);
(*exeenv)->ReleaseStringUTFChars(exeenv, jstring, string);
}


Currently Active Users
Categories
Latest Blog Entries

Rate this article