接上文

例子 flatcc/samples/bugreport

这个例子中用到了emun和自定义file_identifier

namespace Eclectic;

enum Fruit : byte { Banana = -1, Orange = 42 }
table FooBar {
    meal      : Fruit = Banana;
    density   : long (deprecated);
    say       : string;
    height    : short;
}
file_identifier "NOOB";
root_type FooBar;
/* Minimal test with all headers generated into a single file. */
#include "build/myissue_generated.h"
#include "flatcc/support/hexdump.h"

int main(int argc, char *argv[])
{
    int ret;
    void *buf;
    size_t size;
    flatcc_builder_t builder, *B;

    (void)argc;
    (void)argv;

    B = &builder;
    flatcc_builder_init(B);

    Eclectic_FooBar_start_as_root(B);
    Eclectic_FooBar_say_create_str(B, "hello");
    Eclectic_FooBar_meal_add(B, Eclectic_Fruit_Orange);
    Eclectic_FooBar_height_add(B, -8000);
    Eclectic_FooBar_end_as_root(B);
    buf = flatcc_builder_get_direct_buffer(B, &size);
#if defined(PROVOKE_ERROR) || 0
    /* Provoke error for testing. */
    ((char*)buf)[0] = 42;
#endif
    ret = Eclectic_FooBar_verify_as_root(buf, size);
    if (ret) {
        printf("could not verify Electic.FooBar table, got %s\n", flatcc_verify_error_string(ret));
    }
    hexdump("Eclectic.FooBar buffer for myissue", buf, size, stdout);

    flatcc_builder_clear(B);
    return ret;
}
$ ./build/myissue 
Eclectic.FooBar buffer for myissue:
00000000  08 00 00 00 4e 4f 4f 42  e8 ff ff ff 08 00 00 00  |....NOOB........|
00000010  2a 00 c0 e0 05 00 00 00  68 65 6c 6c 6f 00 00 00  |*.......hello...|
00000020  0c 00 0c 00 08 00 00 00  04 00 0a 00              |............|

导出码流的几种方式

函数 说明 注意
flatcc_builder_get_direct_buffer 直接返回flatcc_builder_t结构中的流指针is_default_emitter 效率最高的方法,但注意不能并发。
flatcc_builder_copy_buffer 将is_default_emitter码流复制给传入buffer中  
flatcc_builder_finalize_buffer malloc一块内存然后调用flatcc_builder_copy_buffer 需调用flatcc_builder_free释放内存

identifier

schema中定义的file_identifier会生成,并替换掉默认生成的identifier。

#define flatbuffers_identifier "NOOB"