Saturday, April 20, 2013

jni jnienv GetLongField example c c++ java



Get<type>Field Routines - 
GetLongField


NativeType Get<type>Field(JNIEnv *env, jobject obj,
jfieldID fieldID);

This family of accessor routines returns the value of an instance (nonstatic) field of an object. The field to access is specified by a field ID obtained by calling GetFieldID(). (GetLongField)

The following table describes the Get<type>Field routine name and result type. You should replace type in Get<type>Field with the Java type of the field, or use one of the actual routine names from the table, and replace NativeType with the corresponding native type for that routine.

Table 4-1a Get<type>Field Family of Accessor Routines

Get<type>Field Routine Name

Native Type

GetObjectField()

jobject

GetBooleanField()

jboolean

GetByteField()

jbyte

GetCharField()

jchar

GetShortField()

jshort

GetIntField()

jint

GetLongField()

jlong

GetFloatField()

jfloat

GetDoubleField()

jdouble
LINKAGE:
Indices in the JNIEnv interface function table:
Table 4-1b Get<type>Field Family of Accessor Routines

Get<type>Field Routine Name

Index

GetObjectField()
95

GetBooleanField()
96

GetByteField()
97

GetCharField()
98

GetShortField()
99

GetIntField()
100

GetLongField()
101

GetFloatField()
102

GetDoubleField()
103
PARAMETERS:

env: the JNI interface pointer.

obj: a Java object (must not be NULL).

fieldID: a valid field ID.

RETURNS:

Returns the content of the field.

Example - GetLongField


package timing ;
class Timer {
  private long last_time;
  private String last_comment;
  /** Return time in milliseconds since last call,
   * and set last_comment. */
  native long sinceLast(String comment);
}

This is how it could be programmed using the JNI:
 
extern "C" /* specify the C calling convention */ 
    jdouble Java_Timer_sinceLast (
         JNIEnv *env,           /* interface pointer */
         jobject obj,           /* "this" pointer */
         jstring comment)   /* argument #1 */
{
  // Note that the results of the first three statements
  // could be saved for future use (though the results
  // have to be made "global" first).
  jclass cls = env->FindClass("timing.Timer");
  jfieldId last_time_id = env->GetFieldID(cls, "last_time", "J");
  jfieldId last_comment_id = env->GetFieldID(cls, "last_comment",
                                             "Ljava_lang_String;");

  jlong old_last_time = env->GetLongField(obj, last_time_id);
  jlong new_last_time = calculate_new_time();
  env->SetLongField(obj, last_time_id, new_last_time);
  env->SetObjectField(obj, last_comment_id, comment);
  return new_last_time - old_last_time;
}