5

I would like to call a method through a native java interface, which returns an object.

This is my native method

public native Node getProjectionPoint(double lat, double lon);  

Node class

 public class Node {        
    private String id;
    private double latitude;
    private double longitude;
}

C header file

JNIEXPORT jobject JNICALL Java_org_smartcar_serverdatainterface_shared_services_CppConnector_getProjectionPoint (JNIEnv *env, jobject obj, jdouble lat, jdouble lon);

How could I create an object and return it to java?

Andre Hofmeister
  • 3,185
  • 11
  • 51
  • 74
JanithOCoder
  • 301
  • 2
  • 5
  • 19

2 Answers2

7

I sort out the problem

JNIEXPORT jobject JNICALL Java_org_smartcar_serverdatainterface_shared_services_CppConnector_getProjectionPoint
  (JNIEnv *env, jobject obj, jdouble lat, jdouble lon)
{
    jclass class = (*env)->FindClass(env,"org/smartcar/serverdatainterface/shared/businessentities/Node");

    if (NULL == class)
        PrintError ("class");

    jmethodID cid = (*env)->GetMethodID(env,class, "<init>", "(DD)V");

   if (NULL == cid)
       PrintError ("method");

   return (*env)->NewObject(env, class, cid, lat, lon);
}

this works perfectly

JanithOCoder
  • 301
  • 2
  • 5
  • 19
3

In JNI you have a method

JNIEnv->NewObject() that invokes the actual constructor of a given Java class.

Maybe something like:

JNIEXPORT jobject JNICALL Java_org_smartcar_serverdatainterface_shared_services_CppConnector_getProjectionPoint (JNIEnv *env, jobject obj, jdouble lat, jdouble lon)
{
  jclass cls = env->GetObjectClass(obj);
  jmethodID constructor = env->GetMethodID(cls, "<init>", "(DD)V");
  return env->NewObject(cls, constructor, lat, lon);
}

You should modify your class constructor to receive two parameters. You can also initialize field by field, but it requires to invoke GetFieldID two times in C++.

ebasconp
  • 1,608
  • 2
  • 17
  • 27