protobuf2json-c icon indicating copy to clipboard operation
protobuf2json-c copied to clipboard

json2protobuf_object: Type of protobuf_message

Open dapaulid opened this issue 10 years ago • 1 comments

Considering the following use case:

    int result;
    char error_string[256] = {0};

    const char *initial_json_string = \
    "{\n"
    "  \"name\": \"John Doe\",\n"
    "  \"id\": 42\n"
    "}";
    Foo__Person* pPerson = NULL;

    result = json2protobuf_string((char *)initial_json_string, JSON_REJECT_DUPLICATES,
        &foo__person__descriptor, (ProtobufCMessage**)&pPerson,
        error_string, sizeof(error_string));
    CPPUNIT_ASSERT_EQUAL(result, 0);
    CPPUNIT_ASSERT(pPerson);
    CPPUNIT_ASSERT_EQUAL(pPerson->id, (int32)42);
    CPPUNIT_ASSERT_STREQUAL(pPerson->name, "John Doe");

    free(pPerson);

Why does the message output buffer require to be passed as (ProtobufCMessage**)? In my opinion it should be either (ProtobufCMessage*) or (void*) for the following reasons:

  • Avoids casting on caller side.
  • Leaves allocation up to caller, i.e. the message can be placed on the stack to avoid the overhead of calloc() in json2protobuf_process_message() for performance reasons. The caller needs to know the exact type anyway, as he is required to pass the message descriptor as well.

dapaulid avatar Sep 07 '15 13:09 dapaulid

@dapaulid even if I change json2protobuf_string() signature to "leaves allocation up to caller" it will affect only memory for root-level structure, not for all nested messages and other values. So it does not makes sense to me. I thought about allowing to use custom allocators all over the library code, but does not started this work yet. So if it will be useful for you - pull requests are always welcome.

Sannis avatar Nov 28 '16 21:11 Sannis