Skip to content

Commit

Permalink
Add get_capnp_bytes to python Any
Browse files Browse the repository at this point in the history
  • Loading branch information
dskyle-shieldai authored and dskyle committed Oct 11, 2018
1 parent b499ac2 commit 7bfa666
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 11 deletions.
28 changes: 18 additions & 10 deletions port/python/src/MadaraKnowledge.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,20 @@ class_<T> define_basic_any(const char* name, const char* doc, I init)
using namespace madara::knowledge;
using namespace madara::exceptions;

static auto get_capnp_bytes = [](const T& a) -> object
{
auto buf = a.get_capnp_buffer().asChars();
Py_buffer pybuf;
int err = PyBuffer_FillInfo(&pybuf, 0, (char*)buf.begin(),
buf.size(), true, PyBUF_CONTIG_RO);
if (err == -1)
{
PyErr_Print();
throw madara::exceptions::MadaraException("Bad python buffer");
}
return object(handle<>(PyMemoryView_FromBuffer(&pybuf)));
};

#define MADARA_PYSETITEM(Key, Val) \
.def("__setitem__", +[](T& a, Key key, Val val) { a[key] = val; }, \
"Set an element at the given index to a C++ " #Val)
Expand Down Expand Up @@ -186,18 +200,12 @@ class_<T> define_basic_any(const char* name, const char* doc, I init)
"Check if string indexing is supported")
.def("supports_fields", &T::supports_fields,
"Check if fields are supported")
.def("get_capnp_bytes", +get_capnp_bytes,
"Get a bytes array for the held object. Throws if held object "
"isn't a Cap'n Proto message.")
.def("reader",
+[](const T& a) -> object {
auto buf = a.get_capnp_buffer().asChars();
Py_buffer pybuf;
int err = PyBuffer_FillInfo(&pybuf, 0, (char*)buf.begin(),
buf.size(), true, PyBUF_CONTIG_RO);
if (err == -1)
{
PyErr_Print();
throw madara::exceptions::MadaraException("Bad python buffer");
}
object bytes(handle<>(PyMemoryView_FromBuffer(&pybuf)));
object bytes = get_capnp_bytes(a);
// object bytes(handle<>(PyByteArray_FromStringAndSize(buf.begin(),
// buf.size()))); std::vector<unsigned char> sbuf(buf.begin(),
// buf.begin() + buf.size());
Expand Down
7 changes: 6 additions & 1 deletion port/python/tests/test_any.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
print(b)
print(b.reader())

pose = geo.Pose.new_message();
pose = geo.Pose.new_message()
pose.x = 42
pose.i = 3.14

Expand All @@ -45,6 +45,8 @@

print(c.to_any().reader())

print(c.to_any().get_capnp_bytes())

print(kb.get("zxcv").to_any().reader())

kb.set("apple", 42)
Expand All @@ -53,3 +55,6 @@

print(list(kb.to_map("a")));
print(list(kb.to_map("", ".", "ar")));

b = geo.Pose.from_bytes(c.to_any().get_capnp_bytes())
print(b)

0 comments on commit 7bfa666

Please sign in to comment.