JNI. How to get jstring from jobject and convert it to char*

10,982

jstring dateString = (jstring)(*env)->GetObjectField(env, stat, idDate);

… and after that everything is OK.

Share:
10,982

Related videos on Youtube

Aleksandr
Author by

Aleksandr

Updated on September 15, 2022

Comments

  • Aleksandr
    Aleksandr over 1 year

    This is what I have so far: I pass an object which has 2 fields: String and Integer, as a parameter and I want to send information to process it in C part, which is not important at this point... I get complains at jstring declaration

    JNIEXPORT jint JNICALL Java_Tier3_NativeMethods_totalPalletsIn(
                JNIEnv *env, jclass cls, jobject stat) {
    
    jclass staticsitcs = (*env)->GetObjectClass(env, stat);
    
    // Here I try to get it using the ID
    jfieldID idDate = (*env)->GetFieldID(env, staticsitcs, "date", "S");
    
    jstring dateString = (jstring)(*env)->GetStringRegion(env, stat, idDate);
    
    // Here converting whatever I get in jstring to char*
    char* date = (*env)->GetStringUTFChars(env,dateString,0);
    
    // Getting the 2nd field from the object
    jfieldID idNumber = (*env)->GetFieldID(env, staticsitcs, "amount", "I");
    
    jint amount = (*env)->GetDoubleField(env, stat, idNumber);
    
    // Calling C method
    jint totalPallets = checkTotalPalletsIn(date, amount);
    
    (*env)->ReleaseStringUTFChars(env, dateString, date);
    
    return totalPallets;
    }
    

    What am I missing?

  • Aleksandr
    Aleksandr over 10 years
    Than helped, but now I get "initialization discards «const» qualifier from pointer target type" when I try to pass the date into C method. Any tips on this?
  • Alex Cohn
    Alex Cohn over 10 years
    Did you by any chance declare date as <b>const char *</b>?
  • Aleksandr
    Aleksandr over 10 years
    No, It's just char*. Well.. I figured out that it was just a warning, so nothing major, but now when I compile it I see this: /cygdrive/c/Temp/ccLeMJG9.s: Assembler messages: /cygdrive/c/Temp/ccLeMJG9.s:15: Error: invalid instruction suffix for push' /cygdrive/c/Temp/ccLeMJG9.s:25: Error: operand type mismatch for call' ....
  • Aleksandr
    Aleksandr over 10 years
    Ok, it's fixed now. Used 64bit compiler instead of 32
  • kumarD
    kumarD about 7 years
    @AlexCohn can you please tell how to extract the class name from the Jclass object?
  • kumarD
    kumarD about 7 years
    @AlexCohn i am doing this ot get the method name (*jvmti)->GetMethodName(jvmti,frames[i].method,&methodName,N‌​ULL,NULL); and getting the jclass reference via : (*jvmti)->GetMethodDeclaringClass(jvmti,frames[i].method,&de‌​claring_class_ptr); need help in getting the class name from jclass reference