JNI Passing structs or class objects as parameters from Java to C++

6,430 views
Skip to first unread message

marcpolo

unread,
Jul 9, 2012, 11:47:44 AM7/9/12
to andro...@googlegroups.com
I'd like to call a native function from an android app to retrieve data stored in a struct or class. e.g.

class B
{
    Float param1;
    float param2;
}

class A
{
    static
    {
        System.loadLibrary("MyApp");
    }
    static native void getData(B data);
}

In the native method I try the following

JNIEXPORT
void JNICALL Java_com_pkg_app_MyProg_getData(JNIEnv *env, jclass clazz,  jobject obj)
{
    jclass cls = env->FindClass("com/pkg/app/B");
    jfieldID param1ID = env->GetFieldID(cls, "param1", "F");
    jfieldID param2ID = env->GetFieldID(cls, "param2", "F");
    env->SetFloatField(obj, param1ID, 10.0f);
    env->SetFloatField(obj, param2ID, 5.0f);
}

But get the error "java.lang.NoSuchFieldError" upon the call to GetFieldID.

What am I doing wrong? I've spent most of the day searching for information on this and can only find examples on how to retrieve arrays or call methods on objects.

Any help would be appreciated. Thanks

RichardC

unread,
Jul 9, 2012, 12:23:23 PM7/9/12
to andro...@googlegroups.com
F is a float but it is not a Float (note the upper case F)

marcpolo

unread,
Jul 9, 2012, 1:26:17 PM7/9/12
to andro...@googlegroups.com

Thank you kind sir!!

Using floats rather than Float in the Java app resolved my problem.

Prabhu Konchada

unread,
May 8, 2015, 5:53:49 AM5/8/15
to andro...@googlegroups.com
Can you please help me with the reverse sir


Say I have some C structure 

struct X
{
int a;
int b;
};

want to return it from jni or pass it as a function how should I do that sir.

mic _

unread,
May 8, 2015, 7:36:15 AM5/8/15
to andro...@googlegroups.com
The easiest way in that particular case would probably be to pass the struct's contents to Java as two jint arguments (int in Java), and return them in a jintArray (int[] in Java).

/Michael

--
You received this message because you are subscribed to the Google Groups "android-ndk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to android-ndk...@googlegroups.com.
To post to this group, send email to andro...@googlegroups.com.
Visit this group at http://groups.google.com/group/android-ndk.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages