diff --git a/src/idl_gen_cpp.cpp b/src/idl_gen_cpp.cpp index 3a4324069..e9a708a08 100644 --- a/src/idl_gen_cpp.cpp +++ b/src/idl_gen_cpp.cpp @@ -638,21 +638,27 @@ std::string GenerateCPP(const Parser &parser, "return verifier.VerifyBuffer<"; code += parser.root_struct_def->name + ">(); }\n\n"; + if (parser.file_identifier_.length()) { + // Return the identifier + code += "inline const char *" + parser.root_struct_def->name; + code += "Identifier() { return \"" + parser.file_identifier_; + code += "\"; }\n\n"; + + // Check if a buffer has the identifier. + code += "inline bool " + parser.root_struct_def->name; + code += "BufferHasIdentifier(const void *buf) { return flatbuffers::"; + code += "BufferHasIdentifier(buf, "; + code += parser.root_struct_def->name + "Identifier()); }\n\n"; + } + // Finish a buffer with a given root object: code += "inline void Finish" + parser.root_struct_def->name; code += "Buffer(flatbuffers::FlatBufferBuilder &fbb, flatbuffers::Offset<"; code += parser.root_struct_def->name + "> root) { fbb.Finish(root"; if (parser.file_identifier_.length()) - code += ", \"" + parser.file_identifier_ + "\""; + code += ", " + parser.root_struct_def->name + "Identifier()"; code += "); }\n\n"; - if (parser.file_identifier_.length()) { - // Check if a buffer has the identifier. - code += "inline bool " + parser.root_struct_def->name; - code += "BufferHasIdentifier(const void *buf) { return flatbuffers::"; - code += "BufferHasIdentifier(buf, \"" + parser.file_identifier_; - code += "\"); }\n\n"; - } } CloseNestedNameSpaces(name_space, &code); diff --git a/tests/monster_test_generated.h b/tests/monster_test_generated.h index 62c43c38b..c33ae57bd 100755 --- a/tests/monster_test_generated.h +++ b/tests/monster_test_generated.h @@ -240,9 +240,11 @@ inline const Monster *GetMonster(const void *buf) { return flatbuffers::GetRoot< inline bool VerifyMonsterBuffer(flatbuffers::Verifier &verifier) { return verifier.VerifyBuffer(); } -inline void FinishMonsterBuffer(flatbuffers::FlatBufferBuilder &fbb, flatbuffers::Offset root) { fbb.Finish(root, "MONS"); } +inline const char *MonsterIdentifier() { return "MONS"; } -inline bool MonsterBufferHasIdentifier(const void *buf) { return flatbuffers::BufferHasIdentifier(buf, "MONS"); } +inline bool MonsterBufferHasIdentifier(const void *buf) { return flatbuffers::BufferHasIdentifier(buf, MonsterIdentifier()); } + +inline void FinishMonsterBuffer(flatbuffers::FlatBufferBuilder &fbb, flatbuffers::Offset root) { fbb.Finish(root, MonsterIdentifier()); } } // namespace Example } // namespace MyGame diff --git a/tests/test.cpp b/tests/test.cpp index 9175b5393..f726d615e 100644 --- a/tests/test.cpp +++ b/tests/test.cpp @@ -117,6 +117,7 @@ void AccessFlatBufferTest(const std::string &flatbuf) { flatbuf.length()); TEST_EQ(VerifyMonsterBuffer(verifier), true); + TEST_EQ(strcmp(MonsterIdentifier(), "MONS"), 0); TEST_EQ(MonsterBufferHasIdentifier(flatbuf.c_str()), true); // Access the buffer from the root.