API Reference¶
A python library wrapping the Cap’n Proto C++ library
Example Usage:
import capnp
addressbook = capnp.load('addressbook.capnp')
# Building
addresses = addressbook.AddressBook.newMessage()
people = addresses.init('people', 1)
alice = people[0]
alice.id = 123
alice.name = 'Alice'
alice.email = 'alice@example.com'
alicePhone = alice.init('phones', 1)[0]
alicePhone.type = 'mobile'
f = open('example.bin', 'w')
addresses.write(f)
f.close()
# Reading
f = open('example.bin')
addresses = addressbook.AddressBook.read(f)
for person in addresses.people:
print(person.name, ':', person.email)
for phone in person.phones:
print(phone.type, ':', phone.number)
Classes¶
RPC¶
- class capnp.lib.capnp._RemotePromise¶
- cancel(self)¶
- schema¶
A property that returns the _StructSchema object matching this reader
- to_dict(self, verbose=False, ordered=False)¶
Communication¶
- class capnp.TwoPartyClient(socket=None, traversal_limit_in_words=None, nesting_limit=None)¶
TwoPartyClient for RPC Communication
- Parameters:
socket – AsyncIoStream
traversal_limit_in_words – Pointer derefence limit (see https://capnproto.org/cxx.html).
nesting_limit – Recursive limit when reading types (see https://capnproto.org/cxx.html).
- bootstrap(self)¶
- close(self)¶
- on_disconnect(self)¶
- class capnp.TwoPartyServer(socket=None, bootstrap=None, traversal_limit_in_words=None, nesting_limit=None)¶
TwoPartyServer for RPC Communication
- Parameters:
socket – AsyncIoStream
bootstrap – Class object defining the implementation of the Cap’n’proto interface.
traversal_limit_in_words – Pointer derefence limit (see https://capnproto.org/cxx.html).
nesting_limit – Recursive limit when reading types (see https://capnproto.org/cxx.html).
- bootstrap(self)¶
- close(self)¶
- on_disconnect(self)¶
- capnp.AsyncIoStream¶
alias of
_AsyncIoStream
- class capnp.lib.capnp._AsyncIoStream¶
- close(self)¶
- async static create_connection(host=None, port=None, **kwargs)¶
Create a TCP connection.
All parameters given to this function are passed to asyncio.get_running_loop().create_connection(). See that function for documentation on the possible arguments.
- async static create_server(callback, host=None, port=None, **kwargs)¶
Create a TCP connection server.
The callback parameter will be called whenever a new connection is made. It receives a AsyncIoStream instance as its only argument. If the result of callback is a coroutine, it will be scheduled as a task.
This function behaves similarly to asyncio.get_running_loop().create_server(). All arguments except for callback will be passed directly to that function, and the server returned is similar as well. See that function for documentation on the possible arguments.
- async static create_unix_connection(path=None, **kwargs)¶
Create a Unix socket connection.
All parameters given to this function are passed to asyncio.get_running_loop().create_unix_connection(). See that function for documentation on the possible arguments.
- async static create_unix_server(callback, path=None, **kwargs)¶
Create a unix connection server.
The callback parameter will be called whenever a new connection is made. It receives a AsyncIoStream instance as its only argument. If the result of callback is a coroutine, it will be scheduled as a task.
This function behaves similarly to asyncio.get_running_loop().create_server(). All arguments except for callback will be passed directly to that function, and the server returned is similar as well. See that function for documentation on the possible arguments.
- async wait_closed(self)¶
Capability¶
Response¶
- class capnp.lib.capnp._Response¶
- as_builder(self, num_first_segment_words=None)¶
A method for casting this Reader to a Builder
This is a copying operation with respect to the message’s buffer. Changes in the new builder will not reflect in the original reader.
- Parameters:
num_first_segment_words (int) – Size of the first segment to allocate (in words ie. 8 byte increments)
- Return type:
- is_root¶
is_root: ‘bool’
- schema¶
A property that returns the _StructSchema object matching this reader
- to_dict(self, verbose=False, ordered=False)¶
- total_size¶
- which¶
Returns the enum corresponding to the union in this struct
- Return type:
_DynamicEnumField
- Returns:
A string/enum corresponding to what field is set in the union
- Raises:
KjException
if this struct doesn’t contain a union
Miscellaneous¶
- class capnp.KjException(message=None, nature=None, durability=None, wrapper=None, type=None)¶
KjException is a wrapper of the internal C++ exception type.
There is an enum named Type listed below, and a bunch of fields.
- class Type¶
- DISCONNECTED = 'DISCONNECTED'¶
- FAILED = 'FAILED'¶
- OTHER = 'OTHER'¶
- OVERLOADED = 'OVERLOADED'¶
- UNIMPLEMENTED = 'UNIMPLEMENTED'¶
- reverse_mapping = {'DISCONNECTED': 'DISCONNECTED', 'FAILED': 'FAILED', 'OTHER': 'OTHER', 'OVERLOADED': 'OVERLOADED', 'UNIMPLEMENTED': 'UNIMPLEMENTED'}¶
- add_note(object, /)¶
Exception.add_note(note) – add a note to the exception
- args¶
- property description¶
- property file¶
- property line¶
- property type¶
- with_traceback(object, /)¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- class capnp.SchemaParser¶
A class for loading Cap’n Proto schema files.
Do not use this class unless you’re sure you know what you’re doing. Use the convenience method
load()
instead.- load(self, file_name, display_name=None, imports=[])¶
Load a Cap’n Proto schema from a file
You will have to load a schema before you can begin doing anything meaningful with this library. Loading a schema is much like loading a Python module (and load even returns a ModuleType). Once it’s been loaded, you use it much like any other Module:
parser = capnp.SchemaParser() addressbook = parser.load('addressbook.capnp') print addressbook.qux # qux is a top level constant # 123 person = addressbook.Person.new_message()
- Parameters:
- Return type:
ModuleType
- Returns:
A module corresponding to the loaded schema. You can access parsed schemas and constants with . syntax
- Raises:
exceptions.IOError
if file_name doesn’t existKjException
if the Cap’n Proto C++ library has any problems loading the schema
- modules_by_id¶
modules_by_id: dict
- class capnp.SchemaLoader¶
Class which can be used to construct Schema objects from schema::Nodes as defined in schema.capnp.
This class wraps capnproto/c++/src/capnp/schema-loader.h directly.
- get(self, id_)¶
Gets the schema for the given ID, throwing an exception if it isn’t present.
- load(self, _NodeReader reader)¶
Loads the given schema node. Validates the node and throws an exception if invalid. This makes a copy of the schema, so the object passed in can be destroyed after this returns.
- load_dynamic(self, _DynamicStructReader reader)¶
Loads the given schema node with self.load, but converts from a _DynamicStructReader first.
Functions¶
- capnp.add_import_hook()¶
Add a hook to the python import system, so that Cap’n Proto modules are directly importable
After calling this function, you can use the python import syntax to directly import capnproto schemas. This function is automatically called upon first import of capnp, so you will typically never need to use this function.:
import capnp capnp.add_import_hook() import addressbook_capnp # equivalent to capnp.load('addressbook.capnp', 'addressbook', sys.path), # except it will search for 'addressbook.capnp' in all directories of sys.path
- capnp.remove_import_hook()¶
Remove the import hook, and return python’s import to normal
- capnp.cleanup_global_schema_parser()¶
Unloads all of the schema from the current context
- capnp.kj_loop()¶
Context manager for running the KJ event loop
As long as the context manager is active it is guaranteed that the KJ event loop is running. When the context manager is exited, the KJ event loop is shut down properly and pending tasks are cancelled.
- Raises:
[RuntimeError] – If the KJ event loop is already running (on this thread).
Warning
Every capnp rpc call required a running KJ event loop.
- async capnp.run(coro)¶
Ensure that the coroutine runs while the KJ event loop is running
This is a shortcut for wrapping the coroutine in a
capnp.kj_loop()
context manager.- Parameters:
coro – Coroutine to run
- capnp.load(file_name, display_name=None, imports=[])¶
Load a Cap’n Proto schema from a file
You will have to load a schema before you can begin doing anything meaningful with this library. Loading a schema is much like loading a Python module (and load even returns a ModuleType). Once it’s been loaded, you use it much like any other Module:
addressbook = capnp.load('addressbook.capnp') print addressbook.qux # qux is a top level constant in the addressbook.capnp schema # 123 person = addressbook.Person.new_message()
- Parameters:
- Return type:
ModuleType
- Returns:
A module corresponding to the loaded schema. You can access parsed schemas and constants with . syntax
- Raises:
KjException
if file_name doesn’t exist
Internal Classes¶
These classes are internal to the library. You will never need to allocate one yourself, but you may end up using some of their member methods.
Modules¶
These are classes that are made for you when you import a Cap’n Proto file:
import capnp
import addressbook_capnp
print type(addressbook_capnp.Person) # capnp.capnp._StructModule
- class capnp._InterfaceModule(schema, name)¶
- class capnp._StructModule(schema, name)¶
- from_bytes(self, buf, traversal_limit_in_words=None, nesting_limit=None, builder=False)¶
Returns a Reader for the unpacked object in buf.
- Parameters:
buf (buffer) – Any Python object that supports the buffer interface.
traversal_limit_in_words (int) – Limits how many total words of data are allowed to be traversed. Is actually a uint64_t, and values can be up to 2^64-1. Default is 8*1024*1024.
nesting_limit (int) – Limits how many total words of data are allowed to be traversed. Default is 64.
builder (bool) – If true, return a builder object.
Enabling builder will allow you to change the contents of buf, so do this with care.
- Return type:
- from_bytes_packed(self, buf, traversal_limit_in_words=None, nesting_limit=None)¶
Returns a Reader for the packed object in buf.
- Parameters:
buf (buffer) – Any Python object that supports the readable buffer interface.
traversal_limit_in_words (int) – Limits how many total words of data are allowed to be traversed. Is actually a uint64_t, and values can be up to 2^64-1. Default is 8*1024*1024.
nesting_limit (int) – Limits how many total words of data are allowed to be traversed. Default is 64.
- Return type:
- from_segments(self, segments, traversal_limit_in_words=None, nesting_limit=None)¶
Returns a Reader for a list of segment bytes.
This avoids making copies.
NB: This is not currently supported on PyPy.
- Return type:
- new_message(self, num_first_segment_words=None, **kwargs)¶
Returns a newly allocated builder message.
- Parameters:
Note, kwargs is not an actual argument, but refers to Python’s ability to pass keyword arguments. ie. new_message(my_field=100)
- Return type:
- read(self, file, traversal_limit_in_words=None, nesting_limit=None)¶
Returns a Reader for the unpacked object read from file.
- Parameters:
file (file) – A python file-like object. It must be a “real” file, with a fileno() method.
traversal_limit_in_words (int) – Limits how many total words of data are allowed to be traversed. Is actually a uint64_t, and values can be up to 2^64-1. Default is 8*1024*1024.
nesting_limit (int) – Limits how many total words of data are allowed to be traversed. Default is 64.
- Return type:
- async read_async(self, _AsyncIoStream stream, traversal_limit_in_words=None, nesting_limit=None)¶
Async version of read(). Returns either a message, or None in case of EOF.
- Parameters:
file (AsyncIoStream) – A AsyncIoStream
traversal_limit_in_words (int) – Limits how many total words of data are allowed to be traversed. Is actually a uint64_t, and values can be up to 2^64-1. Default is 8*1024*1024.
nesting_limit (int) – Limits how many total words of data are allowed to be traversed. Default is 64.
- Return type:
- read_multiple(self, file, traversal_limit_in_words=None, nesting_limit=None, skip_copy=False)¶
Returns an iterable, that when traversed will return Readers for messages.
- Parameters:
file (file) – A python file-like object. It must be a “real” file, with a fileno() method.
traversal_limit_in_words (int) – Limits how many total words of data are allowed to be traversed. Is actually a uint64_t, and values can be up to 2^64-1. Default is 8*1024*1024.
nesting_limit (int) – Limits how many total words of data are allowed to be traversed. Default is 64.
skip_copy (bool) – By default, each message is copied because the file needs to advance, even if the message is never read completely. Skip this only if you know what you’re doing.
- Return type:
Iterable with elements of
_DynamicStructReader
- read_multiple_bytes(self, buf, traversal_limit_in_words=None, nesting_limit=None)¶
Returns an iterable, that when traversed will return Readers for messages.
- Parameters:
buf (buffer) – Any Python object that supports the buffer interface.
traversal_limit_in_words (int) – Limits how many total words of data are allowed to be traversed. Is actually a uint64_t, and values can be up to 2^64-1. Default is 8*1024*1024.
nesting_limit (int) – Limits how many total words of data are allowed to be traversed. Default is 64.
- Return type:
Iterable with elements of
_DynamicStructReader
- read_multiple_bytes_packed(self, buf, traversal_limit_in_words=None, nesting_limit=None)¶
Returns an iterable, that when traversed will return Readers for messages.
- Parameters:
buf (buffer) – Any Python object that supports the buffer interface.
traversal_limit_in_words (int) – Limits how many total words of data are allowed to be traversed. Is actually a uint64_t, and values can be up to 2^64-1. Default is 8*1024*1024.
nesting_limit (int) – Limits how many total words of data are allowed to be traversed. Default is 64.
- Return type:
Iterable with elements of
_DynamicStructReader
- read_multiple_packed(self, file, traversal_limit_in_words=None, nesting_limit=None, skip_copy=False)¶
Returns an iterable, that when traversed will return Readers for messages.
- Parameters:
file (file) – A python file-like object. It must be a “real” file, with a fileno() method.
traversal_limit_in_words (int) – Limits how many total words of data are allowed to be traversed. Is actually a uint64_t, and values can be up to 2^64-1. Default is 8*1024*1024.
nesting_limit (int) – Limits how many total words of data are allowed to be traversed. Default is 64.
skip_copy (bool) – By default, each message is copied because the file needs to advance, even if the message is never read completely. Skip this only if you know what you’re doing.
- Return type:
Iterable with elements of
_DynamicStructReader
- read_packed(self, file, traversal_limit_in_words=None, nesting_limit=None)¶
Returns a Reader for the packed object read from file.
- Parameters:
file (file) – A python file-like object. It must be a “real” file, with a fileno() method.
traversal_limit_in_words (int) – Limits how many total words of data are allowed to be traversed. Is actually a uint64_t, and values can be up to 2^64-1. Default is 8*1024*1024.
nesting_limit (int) – Limits how many total words of data are allowed to be traversed. Default is 64.
- Return type:
Readers¶
- class capnp._DynamicListReader¶
Class for reading Cap’n Proto Lists
This class thinly wraps the C++ Cap’n Proto DynamicList::Reader class. __getitem__ and __len__ have been defined properly, so you can treat this class mostly like any other iterable class:
... person = addressbook.Person.read(file) phones = person.phones # This returns a _DynamicListReader phone = phones[0] print phone.number for phone in phones: print phone.number
- class capnp._DynamicStructReader¶
Reads Cap’n Proto structs
This class is almost a 1 for 1 wrapping of the Cap’n Proto C++ DynamicStruct::Reader. The only difference is that instead of a get method, __getattr__ is overloaded and the field name is passed onto the C++ equivalent get. This means you just use . syntax to access any field. For field names that don’t follow valid python naming convention for fields, use the global function
getattr()
:person = addressbook.Person.read(file) # This returns a _DynamicStructReader print person.name # using . syntax print getattr(person, 'field-with-hyphens') # for names that are invalid for python, use getattr
- as_builder(self, num_first_segment_words=None)¶
A method for casting this Reader to a Builder
This is a copying operation with respect to the message’s buffer. Changes in the new builder will not reflect in the original reader.
- Parameters:
num_first_segment_words (int) – Size of the first segment to allocate (in words ie. 8 byte increments)
- Return type:
- is_root¶
is_root: ‘bool’
- schema¶
A property that returns the _StructSchema object matching this reader
- to_dict(self, verbose=False, ordered=False)¶
- total_size¶
- which¶
Returns the enum corresponding to the union in this struct
- Return type:
_DynamicEnumField
- Returns:
A string/enum corresponding to what field is set in the union
- Raises:
KjException
if this struct doesn’t contain a union
- class capnp._PackedFdMessageReader(file, traversal_limit_in_words=None, nesting_limit=None)¶
Read a Cap’n Proto message from a file descriptor in a packed manner
You use this class to for reading message(s) from a file. It’s analagous to the inverse of
_write_packed_message_to_fd()
and_MessageBuilder
, but in one class.:f = open('out.txt') message = _PackedFdMessageReader(f) person = message.get_root(addressbook.Person) print person.name
- Parameters:
fd (int) - A file descriptor
- get_root(self, schema)¶
A method for instantiating Cap’n Proto structs
You will need to pass in a schema to specify which struct to instantiate. Schemas are available in a loaded Cap’n Proto module:
addressbook = capnp.load('addressbook.capnp') ... person = message.get_root(addressbook.Person)
- Parameters:
schema (Schema) – A Cap’n proto schema specifying which struct to instantiate
- Return type:
- Returns:
An object with all the data of the read Cap’n Proto message. Access members with . syntax.
- get_root_as_any(self)¶
A method for getting a Cap’n Proto AnyPointer, from an already pre-written buffer
Don’t use this method unless you know what you’re doing.
- Return type:
_DynamicObjectReader
- Returns:
An AnyPointer that you can read from
- class capnp._StreamFdMessageReader(file, traversal_limit_in_words=None, nesting_limit=None)¶
Read a Cap’n Proto message from a file descriptor
You use this class to for reading message(s) from a file. It’s analagous to the inverse of
_write_message_to_fd()
and_MessageBuilder
, but in one class:f = open('out.txt') message = _StreamFdMessageReader(f) person = message.get_root(addressbook.Person) print person.name
- Parameters:
fd (int) - A file descriptor
- get_root(self, schema)¶
A method for instantiating Cap’n Proto structs
You will need to pass in a schema to specify which struct to instantiate. Schemas are available in a loaded Cap’n Proto module:
addressbook = capnp.load('addressbook.capnp') ... person = message.get_root(addressbook.Person)
- Parameters:
schema (Schema) – A Cap’n proto schema specifying which struct to instantiate
- Return type:
- Returns:
An object with all the data of the read Cap’n Proto message. Access members with . syntax.
- get_root_as_any(self)¶
A method for getting a Cap’n Proto AnyPointer, from an already pre-written buffer
Don’t use this method unless you know what you’re doing.
- Return type:
_DynamicObjectReader
- Returns:
An AnyPointer that you can read from
Builders¶
- class capnp._DynamicResizableListBuilder(parent, field, schema)¶
Class for building growable Cap’n Proto Lists
Warning
You need to call
finish()
on this object before serializing the Cap’n Proto message. Failure to do so will cause your objects not to be written out as well as leaking orphan structs into your message.This class works much like
_DynamicListBuilder
, but it allows growing the list dynamically. It is meant for lists of structs, since for primitive types like int or float, you’re much better off using a normal python list and then serializing straight to a Cap’n Proto list. It has __getitem__ and __len__ defined, but not __setitem__:... person = addressbook.Person.new_message() phones = person.init_resizable_list('phones') # This returns a _DynamicResizableListBuilder phone = phones.add() phone.number = 'foo' phone = phones.add() phone.number = 'bar' phones.finish() f = open('example', 'w') person.write(f)
- add(self)¶
A method for adding a new struct to the list
This will return a struct, in which you can set fields that will be reflected in the serialized Cap’n Proto message.
- Return type:
- finish(self)¶
A method for closing this list and serializing all its members to the message
If you don’t call this method, the items you previously added from this object will leak into the message, ie. inaccessible but still taking up space.
- class capnp._DynamicListBuilder¶
Class for building Cap’n Proto Lists
This class thinly wraps the C++ Cap’n Proto DynamicList::Bulder class. __getitem__, __setitem__, and __len__ have been defined properly, so you can treat this class mostly like any other iterable class:
... person = addressbook.Person.new_message() phones = person.init('phones', 2) # This returns a _DynamicListBuilder phone = phones[0] phone.number = 'foo' phone = phones[1] phone.number = 'bar' for phone in phones: print phone.number
- adopt(self, index, _DynamicOrphan orphan)¶
A method for adopting Cap’n Proto orphans
Don’t use this method unless you know what you’re doing. Orphans are useful for dynamically allocating objects for an unknown sized list.
- Parameters:
index (int) – The index of the element in the list to replace with the newly adopted object
orphan (
_DynamicOrphan
) – A Cap’n proto orphan to adopt. It will be unusable after this operation.
- Return type:
void
- class capnp._DynamicStructBuilder¶
Builds Cap’n Proto structs
This class is almost a 1 for 1 wrapping of the Cap’n Proto C++ DynamicStruct::Builder. The only difference is that instead of a get/set method, __getattr__/__setattr__ is overloaded and the field name is passed onto the C++ equivalent function.
This means you just use . syntax to access or set any field. For field names that don’t follow valid python naming convention for fields, use the global functions
getattr()
/setattr()
:person = addressbook.Person.new_message() # This returns a _DynamicStructBuilder person.name = 'foo' # using . syntax print person.name # using . syntax setattr(person, 'field-with-hyphens', 'foo') # for names that are invalid for python, use setattr print getattr(person, 'field-with-hyphens') # for names that are invalid for python, use getattr
- adopt(self, field, _DynamicOrphan orphan)¶
A method for adopting Cap’n Proto orphans
Don’t use this method unless you know what you’re doing. Orphans are useful for dynamically allocating objects for an unknown sized list.
- Parameters:
field (str) – The field name in the struct
orphan (
_DynamicOrphan
) – A Cap’n proto orphan to adopt. It will be unusable after this operation.
- Return type:
void
- as_reader(self)¶
A method for casting this Builder to a Reader
This is a non-copying operation with respect to the message’s buffer. This means changes to the fields in the original struct will carry over to the new reader.
- Return type:
- clear_write_flag(self)¶
A method used to clear the _is_written flag.
This allows you to write the struct more than once without seeing any warnings.
- copy(self, num_first_segment_words=None)¶
A method for copying this Builder
This is a copying operation with respect to the message’s buffer. Changes in the new builder will not reflect in the original reader.
- Parameters:
num_first_segment_words (int) – Size of the first segment to allocate (in words ie. 8 byte increments)
- Return type:
- disown(self, field)¶
A method for disowning Cap’n Proto orphans
Don’t use this method unless you know what you’re doing.
- Parameters:
field (str) – The field name in the struct
- Return type:
- from_dict(self, dict d)¶
- init(self, field, size=None)¶
Method for initializing fields that are of type union/struct/list
Typically, you don’t have to worry about initializing structs/unions, so this method is mainly for lists.
- Parameters:
- Return type:
- Raises:
KjException
if the field isn’t in this struct
- init_resizable_list(self, field)¶
Method for initializing fields that are of type list (of structs)
This version of init returns a
_DynamicResizableListBuilder
that allows you to add members one at a time (ie. if you don’t know the size for sure). This is only meant for lists of Cap’n Proto objects, since for primitive types you can just define a normal python list and fill it yourself.Warning
You need to call
_DynamicResizableListBuilder.finish()
on the list object before serializing the Cap’n Proto message. Failure to do so will cause your objects not to be written out as well as leaking orphan structs into your message.- Parameters:
field (str) – The field name to initialize
- Return type:
- Raises:
KjException
if the field isn’t in this struct
- is_root¶
is_root: ‘bool’
- schema¶
A property that returns the _StructSchema object matching this writer
- to_bytes(self)¶
Returns the struct’s containing message as a Python bytes object in the unpacked binary format.
This is inefficient; it makes several copies.
- Return type:
- Raises:
KjException
if this isn’t the message’s root struct.
- to_bytes_packed(self)¶
- to_dict(self, verbose=False, ordered=False)¶
- to_segments(self)¶
Returns the struct’s containing message as a Python list of Python bytes objects.
This avoids making copies.
NB: This is not currently supported on PyPy.
- Return type:
- total_size¶
- which¶
Returns the enum corresponding to the union in this struct
- Return type:
_DynamicEnumField
- Returns:
A string/enum corresponding to what field is set in the union
- Raises:
KjException
if this struct doesn’t contain a union
- write(self, file)¶
Writes the struct’s containing message to the given file object in unpacked binary format.
This is a shortcut for calling capnp._write_message_to_fd(). This can only be called on the message’s root struct.
- Parameters:
file (file) – A file or socket object (or anything with a fileno() method), open for write.
- Return type:
void
- Raises:
KjException
if this isn’t the message’s root struct.
- async write_async(self, _AsyncIoStream stream)¶
Async version of of write().
This is a shortcut for calling capnp._write_message_to_fd(). This can only be called on the message’s root struct.
- Parameters:
file (AsyncIoStream) – The AsyncIoStream to write the message to
- Return type:
void
- Raises:
KjException
if this isn’t the message’s root struct.
- write_packed(self, file)¶
Writes the struct’s containing message to the given file object in packed binary format.
This is a shortcut for calling capnp._write_packed_message_to_fd(). This can only be called on the message’s root struct.
- Parameters:
file (file) – A file or socket object (or anything with a fileno() method), open for write.
- Return type:
void
- Raises:
KjException
if this isn’t the message’s root struct.
- class capnp._MallocMessageBuilder(size=None)¶
The main class for building Cap’n Proto messages
You will use this class to handle arena allocation of the Cap’n Proto messages. You also use this object when you’re done assigning to Cap’n Proto objects, and wish to serialize them:
addressbook = capnp.load('addressbook.capnp') message = capnp._MallocMessageBuilder() person = message.init_root(addressbook.Person) person.name = 'alice' ... f = open('out.txt', 'w') _write_message_to_fd(f.fileno(), message)
- get_root(self, schema)¶
A method for instantiating Cap’n Proto structs, from an already pre-written buffer
Don’t use this method unless you know what you’re doing. You probably want to use init_root instead:
addressbook = capnp.load('addressbook.capnp') ... person = message.init_root(addressbook.Person) ... person = message.get_root(addressbook.Person)
- Parameters:
schema (Schema) – A Cap’n proto schema specifying which struct to instantiate
- Return type:
- Returns:
An object where you will set all the members
- get_root_as_any(self)¶
A method for getting a Cap’n Proto AnyPointer, from an already pre-written buffer
Don’t use this method unless you know what you’re doing.
- Return type:
_DynamicObjectBuilder
- Returns:
An AnyPointer that you can set fields in
- get_segments_for_output(self)¶
- init_root(self, schema)¶
A method for instantiating Cap’n Proto structs
You will need to pass in a schema to specify which struct to instantiate. Schemas are available in a loaded Cap’n Proto module:
addressbook = capnp.load('addressbook.capnp') ... person = message.init_root(addressbook.Person)
- Parameters:
schema (Schema) – A Cap’n proto schema specifying which struct to instantiate
- Return type:
- Returns:
An object where you will set all the members
- new_orphan(self, schema)¶
A method for instantiating Cap’n Proto orphans
Don’t use this method unless you know what you’re doing. Orphans are useful for dynamically allocating objects for an unknown sized list, ie:
addressbook = capnp.load('addressbook.capnp') m = capnp._MallocMessageBuilder() alice = m.new_orphan(addressbook.Person)
- Parameters:
schema (Schema) – A Cap’n proto schema specifying which struct to instantiate
- Return type:
- Returns:
An orphan representing a
_DynamicStructBuilder
- set_root(self, value)¶
A method for instantiating Cap’n Proto structs by copying from an existing struct
- Parameters:
value (
_DynamicStructReader
) – A Cap’n Proto struct value to copy- Return type:
void