Search code examples
androidcjsonandroid-ndkjava-native-interface

Convert C Code Into JNI C Code


How would I convert the following C code into JNI C code:

UT_STATIC JsonResult PublishGps(GPS_VARS * vars)
{
    JsonResult result;
    JsonBuilderData jsonBuilderData;

    #define METERS_SECOND_TO_MPH 2.236936

    memset(m_GpsJsonBuffer, 0,GPS_JSON_BUFFER_SIZE );

    InitJsonBuilder(&jsonBuilderData, m_GpsJsonCache, GPS_JSON_CACHE_SIZE, m_GpsJsonBuffer, GPS_JSON_BUFFER_SIZE);


    uint32_t myTest = (uint32_t) vars->rawGps.time;

    (void) PutJsonDateTime(myTest, FIELD(AMERIGO_TIMESTAMP_NAME)); 

    (void) PutJsonLong((int32_t) myTest, FIELD(AMERIGO_EPOCH_NAME)); 

    (void) PutJsonString(vars->dsn, FIELD(AMERIGO_DSN_NAME));

    if (vars->rawGps.mode == 3) 
    { (void) PutJsonString("good", FIELD(AMERIGO_QUALITY_NAME)); }
    else
    {
        { (void) PutJsonString("none", FIELD(AMERIGO_QUALITY_NAME)); }
    }

    (void) PutJsonDouble(AMERIGO_PREC,(float64_t) vars->rawGps.lat, FIELD(AMERIGO_LAT_NAME));

    (void) PutJsonDouble(AMERIGO_PREC, (float64_t) vars->rawGps.lon, FIELD(AMERIGO_LON_NAME));

    float64_t speedMph = (float64_t) vars->rawGps.speed * METERS_SECOND_TO_MPH; 
    (void) PutJsonDouble(AMERIGO_PREC_SPEED, (float64_t) speedMph,FIELD(AMERIGO_SPEED_NAME));

    int32_t heading = (int32_t)vars->rawGps.track; 
    (void) PutJsonLong(heading, FIELD(AMERIGO_HEADING_NAME));

    result = BuildJson(vars->gpsPayLoadBuffer, GPS_PAYLOAD_STRING_SIZE);

    vars->payloadSize = strlen(vars->gpsPayLoadBuffer);

    if (result != jsonSuccess) { ERROR("%s json error %s", __FUNCTION__, JsonStrerr(result)); }

    //reschedule
    vars->nextDrop = vars->dropPeriod + vars->currentTick;

    return result;
}

I'm wondering what I would convert the JsonResult datatype into? Should it be a jstring, jint, etc. What does the JNI code use for the JSON strings or JSON objects? Any help would be greatly appreciated.


Solution

  • Take a look here:

    https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo021

    You have there a sample code where you have JNI wrapper that calls another function in the same shared library.

    What you want to do is:

    • take your data (in Java) and pass it to JNI wrapper (probably via object, serialised string, whatever)
    • inside wrapper code (JNI) you want to create your data structure - GPS_VARS
    • you want to pass it to your function
    • after getting JSON back you want to serialise it to String and return to Java

    You can take a look at samples regarding passing String back and forth between Java and JNI here:

    http://jnicookbook.owsiak.org/recipe-No-009/ http://jnicookbook.owsiak.org/recipe-No-010/

    I hope this helps. Have fun with JNI.