Unmodified C++ object after calling a python callback
Nobody has claimed this yet.
- Dominant language
- C++
- Stars
- 18k
- Forks
- 2.3k
- Avg merge
- 5d 17h
- Merged PRs (30d)
- 10
Description
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
#include <pybind11/pybind11.h>
#include <pybind11/functional.h>
#include <string>
namespace py = pybind11;
// custom type
class MyType {
public:
MyType(int val) :val(val){}
int val;
};
void example_OK(std::function<void(MyType&)> f, MyType& o){
py::print("[example_OK] initial o = ", o);
f(o);
py::print("[example_OK] final o = ", o);
}
void example_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){return std::to_string(o.val);})
.def_readwrite("val", &MyType::val)
;
m.def("example_NOK", &example_NOK);
m.def("example_OK", &example_OK);
}
python code:
import cmake_example as m
def f(o):
o.val = -3
t = m.MyType(10)
m.example_OK(f, t)
m.example_NOK(f)
Ìt produces the following output
[example_OK] initial o = 10
[example_OK] final o = -3
[example_NOK] initial o = 10
[example_NOK] final o = 10
In both case, we expected that the final value of the object was -3.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the reproducible C++ and Python example in the issue, especially the PYBIND11_MODULE bindings and the example_OK/example_NOK entry points. Compare how the callback receives a Python-created object versus the local C++ object, focusing on argument conversion and object lifetime. Done means explaining or correcting the differing mutation behavior and demonstrating the expected final value for both calls.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- cpp, python
- Domain
- api, backend-api-design
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100