c char [] to jstring printf适用于int类型,但不适用于string [英] c char[] to jstring printf works for int type but not for string

查看:125
本文介绍了c char [] to jstring printf适用于int类型,但不适用于string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

他们以这种结构向我们发送数据,然后我们必须通过jni将其传递给我们的Java应用。 / p>

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

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

prints the correct int value e.g 52932, but

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

不打印任何内容。
如果我在Java进程下面使用jni代码,还会收到乱码。

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

向Java发送乱码,例如ÄÎp

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.

我的C语言很基础,因此,如果有人指出我的愚蠢,我将不胜感激。在这里做。谢谢,

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

推荐答案

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

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

输出:

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

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

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?

这篇关于c char [] to jstring printf适用于int类型,但不适用于string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆