获取avro字符串时出错

时间:2017-08-01 13:12:42

标签: c serialization avro

我正在尝试使用av​​ro-c做一个简单的字符串setter getter程序。

我的代码是:

avro_value_t frame_value;
avro_schema_t frame_schema = avro_schema_string();
avro_value_iface_t *frame_iface = avro_generic_class_from_schema(frame_schema);
avro_generic_value_new(frame_iface, &frame_value);

char *name;
int size;

avro_value_set_string(&frame_value,"hello");
avro_value_get_string(&frame_value,name,&size);
printf("\nname is %s",name);
printf("\nsize is %d",size);

但它输出一个空字符串,虽然大小正确,包括空字符6。我做错了什么?

1 个答案:

答案 0 :(得分:0)

必须是以下内容,请注意&name而不是name

avro_value_get_string(&frame_value, &name, &size);

因为函数需要一个指向常量字符的双指针。有必要将引擎盖下的指针设置为由setter设置的内部字符数组。

请参阅here in the API documentation

int avro_value_get_string(const avro_value_t *value,
                          const char **dest, size_t *size);

同时让您的name指针指向不变的字符,sizesize_t类型而不是int

const char *name;
size_t size;

使用avro_generic_value_new之后,您必须在使用后释放空间:

avro_generic_value_free(&frame_value);

你还必须使用:

avro_value_iface_decref(frame_iface);
avro_schema_decref(frame_schema);

由于API确实引用了计数,因此在使用后必须释放空间。

此外,我建议始终检查函数的返回值,它们是int或指针,其含义由API documentation解释:

  

Avro C库中的大多数功能都会返回单个int状态代码。遵循POSIX errno.h约定,状态代码0表示成功。非零代码表示错误情况。某些函数返回指针值而不是int状态代码;对于这些函数,NULL指针指示错误。

     

您可以使用avro_strerror函数检索最近错误的字符串描述:

avro_schema_t  schema = avro_schema_string();
if (schema == NULL) {
   fprintf(stderr, "Error was %s\n", avro_strerror());
}