You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I have a C++ code which calls a python function. This function modifies an object passed as its argument. When this object has been instantiated from python, modifications done by the python function are available to the c++ side.
However, an object, directly instantiated from the C++ side, is not modified after the function call.
The following example illustrates this behavior. With the function example_NOK, the object o1 is unmodified after the python function call. This is not the case with example_OK.
Is there a way to fix this issue and have my C++ object modified ?
Thanks for your help.
Reproducible example code
#include<pybind11/pybind11.h>
#include<pybind11/functional.h>
#include<string>namespacepy= pybind11;
// custom typeclassMyType {
public:MyType(int val) :val(val){}
int val;
};
voidexample_OK(std::function<void(MyType&)> f, MyType& o){
py::print("[example_OK] initial o = ", o);
f(o);
py::print("[example_OK] final o = ", o);
}
voidexample_NOK(std::function<void(MyType&)> f){
MyType o1(10);
py::print("[example_NOK] initial o = ", o1);
f(o1);
py::print("[example_NOK] final o = ", o1);
}
PYBIND11_MODULE(cmake_example, m) {
py::class_<MyType>(m, "MyType")
.def(py::init<int>())
.def("__str__", [](MyType& o){returnstd::to_string(o.val);})
.def_readwrite("val", &MyType::val)
;
m.def("example_NOK", &example_NOK);
m.def("example_OK", &example_OK);
}
If this is indeed the issue, then the stop gap would be to write either a specific shim (like what I did) or a general shim where you effectively want to specify py::return_value_policy::reference rather than py::return_value_policy::automatic (which the docs say is ...::copy for lvalue references). (I may try this out shortly, will let you know if I do.)
A longer-term solution might be to have some way to say that you want lvalue arguments to default to reference if a copy is not necessary.
Issue description
Hi,
I have a C++ code which calls a python function. This function modifies an object passed as its argument. When this object has been instantiated from python, modifications done by the python function are available to the c++ side.
However, an object, directly instantiated from the C++ side, is not modified after the function call.
The following example illustrates this behavior. With the function example_NOK, the object o1 is unmodified after the python function call. This is not the case with example_OK.
Is there a way to fix this issue and have my C++ object modified ?
Thanks for your help.
Reproducible example code
python code:
Ìt produces the following output
In both case, we expected that the final value of the object was -3.
The text was updated successfully, but these errors were encountered: