c char []到jstring printf适用于int类型但不适用于字符串

时间:2018-06-12 08:37:45

标签: c arrays string char java-native-interface

我们有供应商提供的api,其结构定义为

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

他们向我们发送了这个结构中的数据,然后我们必须通过jni传递给我们的java应用程序。

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

打印正确的int值,例如52932,但

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

什么都不打印。 如果我在我的java进程下面使用jni代码,那么就会收到乱码。

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

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

向java发送乱码,例如ÄÎ

   // 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.

我的C技能非常基础,所以如果有人能指出我在这里做的愚蠢,我真的很感激。谢谢,

1 个答案:

答案 0 :(得分:0)

我会试一试。我尝试了你的代码,但没有得到相同的行为

#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;
}

输出:

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

我不明白为什么使用格式说明符%s,在你的情况下返回一个空字符串。 除此之外,我不明白你使用%i的原因。这样做时应该收到警告:

$ 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);

你能说明你如何初始化你的结构吗?