Click here to Skip to main content
15,569,840 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I have to return a array of structure values from c++ (jni) to java. I have the c++ struture as follows

byte *Data;
int dataLength;
int width;
int height;

And i have my java structure as

public class MyJavaStructure
public byte[] Data;
public int dataLength;
public int width;
public int height;
And My is

  MyJavaStructure[] mystr =  MyJavaStructure[4]; 
public native int Process();
public LSImage getValues()
     return this.mystr ;
public void setValues(MyJavaStructure bDetails)
     this.mystr = bDetails; 

I tried to pass Object array (MyJavaStructure) directly from JNI using GetMethodId of setValues.

My JNI code is

JNIEXPORT jint JNICALL Java_TestJNI_Process(JNIEnv *jEnv, jobject jObj)

    MyCStructure* mycstr = new MyCStructure[4];

    iRet = Process(&mycstr);

    jclass jClass = jEnv->GetObjectClass(jObj);
    jmethodID constructor;

    jmethodID jObjectID = jEnv->GetMethodID (jLegendClass, "setValues", "(LMyCStructure;)V");
    if (jObjectID == NULL)
        throwJavaException(jEnv, "Unable to find the method setValues");
        return NULL;
    jEnv->CallObjectMethod(jObj, jObjectID, (jobject *) mycstr);

    printf ("After setting the output data value\n");


    return iRet;

The value returned in mycstr contains 4 array of structure (MyCStructure) values and i tried to assign in a MyJavaStructure class object but it returned null.

Am i doing right or is there i have to change anything ?
Matthew Faithfull 12-Feb-13 6:03am    
No, you're not doing it right or it would be working. From a C++ point of view it looks OK and I don't have enough Java to give you a solution but I do have a question which might point you in the right direction. Your MyCStructure contains a pointer but I don't see any way in which JNI can work out how much data this points to. It can't know that you're storing that info elsewhere in the structure. Given that there's no way it can be generating code to copy the data so it would have to effectively be doing a cast to the Java structure. I don't know what byte[] produces in terms of runtime memory layout in Java but I doubt that it is a single 4 or 8 byte pointer, more likely some sort of array structure with a header similar to the whole structure you're using. I believe this is the root of your problem.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900