Dynamically reading schema const property at runtime (c++)

49 views
Skip to first unread message

Daniel Koohmarey

unread,
Jun 8, 2022, 1:33:02 PM6/8/22
to Cap'n Proto

Given the following dummy schema test.capnp:

struct Person {
   const type :Text = "person.type.example";
   version @0 :UInt32;
   name @1 :Text;
}

At runtime, how can we read the default const value from a schema struct (i.e the "person.type.example" above? (type is not considered a field within the struct, but it does appear as a node in the proto):

std::string schema_filename = "test.capnp"; kj::ArrayPtr<const kj::StringPtr> import_paths;
capnp::SchemaParser parser;
capnp::ParsedSchema schema = parser.parseDiskFile( schema_filename.c_str(), 
                                                                         schema_filename.c_str(), import_paths);
auto person_maybe = schema.findNested("Person");
auto* person_schema = kj::_::readMaybe(person_maybe);

// how can I read "person.type.example" out of the Person struct?

Any guidance on the matter is appreciated, thanks!

Kenton Varda

unread,
Jun 8, 2022, 2:13:56 PM6/8/22
to Daniel Koohmarey, Cap'n Proto
Hi Daniel,

I think you can do:

    capnp::ConstSchema type = schema.getNested("Person").getNested("type").asConst();

But it's been a long time since I touched this.

By the way, please do not use stuff in kj::_ directly, that is a private namespace. To read a Maybe, use KJ_IF_MAYBE, KJ_ASSERT_NONNULL, KJ_UNWRAP_OR, etc.

-Kenton

--
You received this message because you are subscribed to the Google Groups "Cap'n Proto" group.
To unsubscribe from this group and stop receiving emails from it, send an email to capnproto+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/capnproto/389bc2ea-3279-4ddc-b8cc-f554d636767fn%40googlegroups.com.

Daniel Koohmarey

unread,
Jun 8, 2022, 2:30:05 PM6/8/22
to Cap'n Proto
Appreciate the reply Kenton, that got me to the solution I was looking for:

std::string type = person_schema->getNested("type").asConst().as<capnp::Text>().cStr();

And will do on avoiding kj::_. Thanks again!


Reply all
Reply to author
Forward
0 new messages