Search code examples
javaandroid-ndkjava-native-interface

how to pass structure from c code to java using Jni


I have to pass a structure

   struct Info {
    u_int8_t timestamp[8];
    u_int32_t  a;
    u_int32_t  b;
    u_int32_t  c;
    ActiveInfo activeInfo[MAX_ACTIVE_SET];

   };

 struct ActiveInfo
{
   u_int8_t  is_reference;
   u_int16_t p;
   u_int32_t q;
    u_int8_t  r;
   u_int8_t  s;
  };
  typedef struct ActiveInfo ActiveInfo;

I want to pass this (Info) structure to my java code.I have goggled,but not get complete ways to do this.

Thanks.


Solution

  • The structure must be defined at Java side, as a class with members. The fact is that JNI allows C to access Java objects, but not Java to access C objects (structs). So if you want to "pass" something through JNI and have it accessible on both sides, it must be a Java object, then qualified as jobject in the interface. From C side then, you have two options:

    • either access the members directly with GetFieldID() and Get/Set<Type>Field, though it's more complicated with arrays (you got some i see)
    • or create Java methods in that class for filling up and reading in simplified fashion, and invoke them with Invoke<Retval>Method

    It depends on design of your data storage. You perhaps want only one side (C or Java) to read and the other to write, which can be reflected in the design conveniently.

    Edit:

    Example can be found at site pointed out by @asgoth : www.steveolyo.com. There is a chapter named "Passing C Structures from C to Java" but then it silently explains how to reflect requried C structure in Java class and pass Java object into C via JNI - which is exactly what my response says.