c char[]to jstring printf适用于int类型,但不适用于string
我们有一个供应商提供的api,其结构定义为c char[]to jstring printf适用于int类型,但不适用于string,c,arrays,string,char,java-native-interface,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进程下
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语言技能非常初级,如果有人能指出我在这里做的蠢事,我将不胜感激。谢谢,我来试一试。我尝试了你的代码,但没有得到相同的行为
#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;
}
我不明白为什么在您的案例中使用格式说明符%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);
您可以演示如何初始化结构吗?您可以演示如何初始化结构吗?它的数据通过网络传输,结构由供应商代码初始化。我们只是获取提取数据的结构。不要假设每个字符数组都是“C样式字符串”。可能数据之间存在
“\0”
,并且没有典型的语义。任何类型的广播结构都是高度不可移植的。我怀疑duo_字,它们表示64位整数。在C语言中,char已被广泛用作8位字节的通用类型(历史悠久,当前有一些变化)。一般来说,源代码不足以记录协议。感谢您的尝试。。。它的实际printf(“值i:%i\n”,l\u duo\u word);非printf(“值i:%i\n”,l\u duo\u word.duo\u word);不知何故,printf成功地正确打印了整个结构的实例。。。
$ 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);