Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[question] Python + C++ full example? #62

Open
harsszegi opened this issue Feb 16, 2023 · 0 comments
Open

[question] Python + C++ full example? #62

harsszegi opened this issue Feb 16, 2023 · 0 comments

Comments

@harsszegi
Copy link

harsszegi commented Feb 16, 2023

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?)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant