0

I'm just starting out experimenting with cap'n proto and trying to improve my understanding.

Right now I'm trying to work out how best to use AnyPointer and whilst experimenting I noticed that I didn't seem to need to call initAs for my object and the values I set would be read in correctly.

This is my schema for a root container that has any kind of struct object

struct TestObject
{
  value1 @0 : Int32 = -5;
  value2 @1 : Float32 = 9.4;
}

struct TestContainer
{
  object @0: AnyPointer;
}

When I come to serialise some objects it does not seem to matter whether I use initAs or getAs.

    ::capnp::MallocMessageBuilder message;
    auto container= message.initRoot<TestContainer>();

    auto anything = container.initObject();              
    auto objectBuilder = anything.getAs<TestObject>();  //I was expecting this to break since nothing obviously initialises it.
    objectBuilder.setValue1( -2099 );
    objectBuilder.setValue2( -3.994f );

    //using initAs works as well
     auto anything = container.initObject();    
    auto objectBuilder = anything.initAs<TestObject>();      
    objectBuilder.setValue1( 270001 );
    objectBuilder.setValue2( -65.2f );

When I deserialise again I get the correct values back from either of the above methods. Is using getAs here correct or would a more complicated TestObject break things?

David Woo
  • 749
  • 4
  • 13

1 Answers1

0

From Cap'n Proto's website https://capnproto.org/cxx.html#structs

getBar(): For primitives, returns the value. For composites, returns a Builder for the composite. If a composite field has not been initialized (i.e. this is the first time it has been accessed), it will be initialized to a copy of the field’s default value before returning.

So yes - You don't have to call init{field}() but can just call get{field}() for any struct type not just AnyPointer.

You do have to call init{field} when it's a list though.

David Woo
  • 749
  • 4
  • 13