【问题标题】:set arrary data to Avro array type with C language用C语言将数组数据设置为Avro数组类型
【发布时间】:2016-12-03 00:31:43
【问题描述】:

我正在使用 Objective-C 进行编程。我正在使用Apache Avro 进行数据序列化。

我的 avro 架构是这样的:

{
"name": "School",
"type":"record",
"fields":[
  {
   "name":"Employees",
   "type":["null", {"type": "array",  
                    "items":{
                       "name":"Teacher",
                       "type":"record",
                       "fields":[
                          {"name":"name", "type":"string"}
                          {"name":"age", "type":"int"}
                       ]
                    }
                  }
          ],
   "default":null
  }
] 
}

在我的 Objective-C 代码中,我有一个 Teacher 对象数组,每个教师对象包含 nameage 的值。

我想使用 Avro 将教师数组数据写入文件,其架构如上所示。我主要关心如何将数据写入上述架构中定义的Employees 数组。

这是我的代码(我必须使用C风格的代码来做,我跟着Avro C documentation):

// I don't show this function, it constructs the a `avro_value_t` based on the schema. No problem here.
avro_value_t school = [self constructSchoolValueForSchema];

// get "Employees" field
avro_value_t employees;
avro_value_get_by_name(school, "employees", &employees, 0);

int idx = 0;
for (Teacher *teacher in teacherArray) {
   // get name and age
   NSString *name = teacher.name;
   int age = teacher.age;

   // set value to avro data type.
    // here 'unionField' is the field of 'Employees', it is a Avro union type which is either null or an array as defined in schema above
   avro_value_t field, unionField;
   avro_value_set_branch(&employees, 1, &unionField);
   // based on documentation, I should use 'avro_value_append'
   avro_value_append(&employees, name, idx);
   // I get confused here!!!! 
   // in above line of code, I append 'name' to 'employees', 
   //which looks not correct, 
   //  because the 'Employees' array is an array of 'Teacher', not arrary of 'name' 
   // What is the correct way to add teacher to 'employees' ? 

   idx ++;
}

我想问的问题其实就在上面的代码注释中。

我正在关注 Avro C 文档,但我迷路了如何将每个 teacher 添加到 employees ?在我上面的代码中,我只是将每个老师的name 添加到了employees 数组中。

【问题讨论】:

    标签: ios objective-c c schema avro


    【解决方案1】:

    我认为您的代码有两个问题,但我对 Avro 不熟悉,所以我不能保证其中之一。我只是快速浏览了您链接的文档,这就是我对avro_value_append 的理解:

    创建一个新元素,即Teacher,并且返回通过第二个参数中的引用(因此它按引用返回)。我的猜测是,您需要使用其他 avro... 方法来填充该元素(即设置教师姓名等)。最后,这样做:

    avro_value_t teacher;
    size_t idx;
    avro_value_append(&employees, &teacher, &idx); // note that idx is also returned by reference and now contains the new elements index
    

    我不确定你是否正确设置了员工,顺便说一句,我没有时间调查。

    第二个问题会在您使用name 时出现。我假设 Avro 需要 C 字符串,但您在这里使用 NSString。您必须对其使用getCString:maxLength:encoding: 方法来填充准备好的缓冲区,以创建可以在Avro 中传递的C 字符串。您也可以使用UTF8String,但请阅读其文档:您可能必须复制内存(memcpy shenanigans),否则您的 Avro 容器会将其数据从其脚下滑走。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-23
      • 2021-10-04
      • 2021-11-17
      • 2019-05-15
      • 2021-08-29
      • 2020-07-03
      相关资源
      最近更新 更多