pybind11_json
pybind11_json copied to clipboard
[question] Python + C++ full example?
Hi,
sorry for being lame but I can't put together a complete working example with pybind11_json. Here is what I need to do:
1.) I have a native C++ class like class Foo { public: int member1; int member2; };
2.) I have the corresponding pybind11 class_ mapping which defines a "Foo" class and does ".def_readwrite" on "member1" and "member2"
3.) Now I need to have to create something which automatically makes it possible that from Python I could:
foo = Foo() foo.member1 = 1 foo.member2 = 2 jsonFoo = json(foo) print(jsonFoo) // This would print '{ member1 : 1, member2 : 2 }'
// ??? foo2 = json('{ member1: 4, member2 : 5}') print(foo2.member1) // this would print 4 print(foo2.member2) // this would print 5
Is it possible at all? Or do I have to create Nlohmann boilerplate code to be able to "Jsonify" my "Foo" class? What is the full workflow here to be able to serialize back and forther PyBind11 classes in Python? Thanks,
p.s. I have tried using the "implicitly_convertible" trick
pythonbind::class_nl::json(mod, "Json") .def(py::init<>()) .def(py::initpy::object()); py::implicitly_convertible<py::object, nl::json>();
and then from Python:
foo = Foo() jsonFoo = Json(foo) json.dumps(jsonFoo)
but that gives me "to_json not implemented for this type of object: xxxx_pybind11.Foo object at XXXXX" (which I suppose is not a surprise, as the C++ PyBind classes are not iterable objects, hence you need to write for each and every Pybind class its own Json converter, I suppose?)