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?

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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++.

7 Comments

Buff... Maybe it's better to copy it, don't you think?
Sorry, I misunderstood your question; I edited my answer accordingly.
I'm getting this error "error: request for member 'GetObjectClass' in something not a structure or union"
Are you including jni.h ?
GetObjectClass would work in this case because the method is an instance method in the same class as the object to be created. I would find it confusing. FindClass is clearer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.