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¶
Promise¶
-
capnp.
Promise
¶ alias of
capnp.lib.capnp._Promise
Promise may be one of:
-
class
capnp.lib.capnp.
_Promise
(obj=None)¶ -
attach
(self, *args)¶
-
cancel
(self, numParents=1)¶
-
is_consumed
¶ is_consumed: ‘bool’
-
then
(self, func, error_func=None)¶
-
wait
(self)¶
-
-
class
capnp.lib.capnp.
_RemotePromise
¶ -
a_wait
(self)¶ Asyncio version of wait(). Required when using asyncio for socket communication.
Will still work with non-asyncio socket communication, but requires async handling of the function call.
-
as_pypromise
(self)¶
-
cancel
(self, numParents=1)¶
-
is_consumed
¶ is_consumed: ‘bool’
-
schema
¶ A property that returns the _StructSchema object matching this reader
-
then
(self, func, error_func=None)¶ Promise pipelining, use to queue up operations on a promise before executing the promise.
-
to_dict
(self, verbose=False, ordered=False)¶
-
wait
(self)¶ Wait on the promise. This will block until the promise has completed.
-
Communication¶
-
class
capnp.
TwoPartyClient
(socket=None, traversal_limit_in_words=None, nesting_limit=None)¶ TwoPartyClient for RPC Communication
Can be initialized using a socket wrapper (libcapnp) or using asyncio controlled sockets.
- Parameters
socket – Can be a string defining a socket (e.g. localhost:12345) or a file descriptor for a socket. Passes socket directly to libcapnp. Do not use with asyncio.
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)¶
-
on_disconnect
(self)¶
-
read
(self, bufsize)¶ libcapnp reader (asyncio sockets only)
- Parameters
bufsize – Buffer size to read from the libcapnp library
-
write
(self, data)¶ libcapnp writer (asyncio sockets only)
- Parameters
data – Buffer to write to the libcapnp library
-
class
capnp.
TwoPartyServer
(socket=None, bootstrap=None, traversal_limit_in_words=None, nesting_limit=None)¶ TwoPartyServer for RPC Communication
Can be initialized using a socket wrapper (libcapnp) or using asyncio controlled sockets.
- Parameters
socket – Can be a string defining a socket (e.g. localhost:12345, also supports *:12345) or a file descriptor for a socket. Passes socket directly to libcapnp. Do not use with asyncio.
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)¶
-
on_disconnect
(self)¶
-
poll_forever
(self)¶ Poll libcapnp library forever (asyncio)
-
poll_once
(self)¶ Poll libcapnp library one cycle.
-
port
¶
-
port_promise
¶ port_promise: object
-
read
(self, bufsize)¶ libcapnp reader (asyncio sockets only)
- Parameters
bufsize – Buffer size to read from the libcapnp library
-
run_forever
(self)¶
-
write
(self, data)¶ libcapnp writer (asyncio sockets only)
- Parameters
data – Buffer to write to the libcapnp library
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 the message (in words ie. 8 byte increments)
- Return type
_DynamicStructBuilder
-
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'}¶
-
-
args
¶
-
property
description
¶
-
property
file
¶
-
property
line
¶
-
property
type
¶
-
with_traceback
()¶ Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
-
class
-
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
-
Functions¶
-
capnp.
add_import_hook
(additional_paths=[])¶ 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
- Parameters
additional_paths (list) – Additional paths, listed as strings, to be used to search for the .capnp files. It is prepended to the beginning of sys.path. It also affects imports inside of Cap’n Proto schemas.
-
capnp.
cleanup_global_schema_parser
()¶ Unloads all of the schema from the current context
-
capnp.
create_event_loop
(threaded=True)¶ Create a new global event loop. This will not remove the previous EventLoop for you, so make sure to do that first
-
capnp.
getTimer
()¶ Get libcapnp event loop timer
-
capnp.
join_promises
(promises)¶
-
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
-
capnp.
poll_once
()¶ Poll libcapnp event loop once
-
capnp.
remove_event_loop
(ignore_errors=False)¶ Remove the global event loop
-
capnp.
remove_import_hook
()¶ Remove the import hook, and return python’s import to normal
-
capnp.
reset_event_loop
(ignore_errors=False, threaded=True)¶ Removes event loop, then creates a new one. See remove_event_loop and create_event_loop for more details.
-
capnp.
wait_forever
()¶ Use libcapnp event loop to poll/wait forever
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. This 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
num_first_segment_words (int) – Size of the first segment to allocate in the message (in words ie. 8 byte increments)
kwargs (dict) – A list of fields and their values to initialize in the struct. Note, this 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
-
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 the message (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' people.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 the message (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.
-
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
-