c char[] to jstring printf works for int type but

2019-09-03 14:34发布

问题:

We have a vendor supplied api which has a struct defined as

typedef   struct 
{ 
    char duo_word[8]; 
} duo_word;

They send us data in this structure which we then have to pass to our java app through jni.

printf("Number:  : %i\n", duo_word_inst);

prints the correct int value e.g 52932, but

printf("Number:  : %s\n", duo_word_inst); 

prints nothing. More over if I use jni code below my java process receives gibberish.

jstring jstrBuf = (*env)->NewStringUTF(env, (char*)(duo_word_inst));

(*env)->SetObjectField(env, *ret_obj, fld_id, jstrBuf);

sends gibberish to java e.g ÄÎ

   // I have got some example data captured from VS debugger below.
   duo_word duo_word_inst = { .duo_word = { 'º', '\b', '\x1', '\0', 'À', '\xe', '2', 'a' } };

    printf("          %i ", duo_word_inst); // gives 67770 which is correct.

My C skills are very elementary so I would really appreciate if some one could point out the silliness I am doing here. Thanks,

回答1:

I'll give it a shot. I tried your code, but don't get the same behavior

#include <stdio.h>

typedef struct 
{
    char duo_word[8];
}duo_word_t;

int main (int p_argc, char *p_argv[])
{   
    duo_word_t l_duo_word = 
    {
        .duo_word = {'1','2','3','4'} 
    };

    /** Works fine. */
    printf("value s: %s\n", l_duo_word.duo_word);

    /** Doesn't work. */
    printf("value i: %i\n", l_duo_word.duo_word);

    return 0;
}

output:

$ ./test 
value s: 1234
value i: 159754736

I don't see why using the format specifier %s, returns an empty string in your case. Besides that I don't get why you are using %i. You should get a warning when doing so:

$ gcc test.c -Wall -Wpedantic -o test
test.c: In function ‘main’:
test.c:19:16: warning: format ‘%i’ expects argument of type ‘int’, but argument 2 has type ‘char *’ [-Wformat=]
         printf("value i: %i\n", l_duo_word.duo_word);

Could you show how you initialize your structure?