Datatypes in Java and in C are not directly related. When you call C programs from Java, you need to pass arguments and accept the returned results or create Java objects in the C program. This requires you to handle primitive datatypes, arrays, and strings coded in C.
Primitive Datatypes
To establish communication between the Java and C datatypes, you must define native equivalents to the Java primitive datatypes, which are then used in the C code as representatives of the Java primitive datatypes.
| Java Datatype | Native Language Equivalent |
| Void | void |
| Byte | jbyte |
| Boolean | jboolean |
| Char | jchar |
| Short | jshort |
| Int | jint |
| Long | jlong |
| Float | jfloat |
| Double | jdouble |
Following code shows how to access an integer variable declared in a Java program in C and modify it:
class JMapC
{
static int send;
//Declaring the native method
private native void intMapjint();
public static void main(String args[])
{
JMapC map = new JMapC();
JMapC.send = 100;
System.out.println("In Java:");
System.out.println(" JMapC.send = " + JMapC.send);
//Invoking the native method
map.intMapjint();
System.out.println("Back in Java:");
System.out.println(" JMapC.send = " + JMapC.send);
}
static
{
//loading library
System.loadLibrary("Demo_lib");
}
}
The following code shows how to generate the header file for the JMapC file
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class JMapC */
#ifndef _Included_JMapC
#define _Included_JMapC
#ifdef __cplusplus
extern "C"
{
#endif
/* Inaccessible static: send */
/*
* Class: JMapC
* Method: intMapjint
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_JMapC_intMapjint (JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
The following code shows how to generate the header file for the JMapC file:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class JMapC */
#ifndef _Included_JMapC
#define _Included_JMapC
#ifdef __cplusplus
extern "C"
{
#endif
/* Inaccessible static: send */
/*
* Class: JMapC
* Method: intMapjint
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_JMapC_intMapjint (JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
The following code shows how to implement the intMapJint method:
#include <stdio.h>
#include <jni.h>
#include "JMapC.h"
JNIEXPORT void JNICALL
Java_JMapC_intMapjint(JNIEnv *exeenv, jobject javaobj)
{
jclass cls = (*exeenv)->GetObjectClass(exeenv, jaavobj);
jfieldID fid;
jint num;
printf("\nAccessing send in C:\n");
fid = (*exeenv)->GetStaticFieldID(exeenv, cls, "send", "I");
if (fid == 0)
{
return;
}
num = (*exeenv)->GetStaticIntField(exeenv, cls, fid);
printf("JMapC.send = %d\n\n", num);
printf("Modifying the value send\n\n");
(*exeenv)->SetStaticIntField(exeenv, cls, fid, num*9);
}
Next Article:- How To Use Java Arrays In C?


Currently Active Users
Categories
Latest Blog Entries

Rate this article