altralaser
altralaser

Reputation: 2073

How to handle struct-like jobject in JNI

I have a question using the Java Native Interface. I've the following class:

public class TestJNI {
  public static native long sendCommand(int id, MyParms param);

  static {
    System.loadLibrary("TestNative");
  }
}

MyParams looks like this:

public class MyParams {
  public String lpstrElementName;
}

And then I have a C file:

#include <jni.h>
#include "TestJNI.h"

JNIEXPORT jlong JNICALL Java_TestJNI_sendCommand
  (JNIEnv *env, jclass clazz, jint id, jobject param)
{
  // code
}

What I don't know at this point is how to handle the jobject parameter and how I can access my element name attribute?

Upvotes: 0

Views: 807

Answers (1)

Constantin M&#252;ller
Constantin M&#252;ller

Reputation: 1290

This is a short example for accessing an integer class field, for more information use the links Jorn Vernee already posted.

class MyParms
{
  int myVar;
}

Function for reading the value of myVar:

JNIEXPORT jlong JNICALL Java_TestJNI_sendCommand
  (JNIEnv *env, jclass clazz, jint id, jobject param)
{
  jfieldID jfid;
  jclass jclass;
  jint val;

  jclass = (*env)->GetObjectClass( env, param );
  jfid   = (*env)->GetFieldID( env, jclass, "myVar", "I");
  val    = (*env)->GetIntField( env, param, jfid );
}

Edit: For accessing a string field...

env->GetFieldID( clazz, "myVar", "Ljava/lang/String;" );

For more information see here and here.

Upvotes: 1

Related Questions