0

I have a c++ function like:

int add(int *i, int j) {
    *i += 3;
    return *i + j;
}

I have created python binding for it using pybind11 as

PYBIND11_MODULE(example, m) {
    m.doc() = R"pbdoc(add)pbdoc";
    m.def("add", &add, R"pbdoc(Add two numbers)pbdoc");
}

I call it in python as:

>>import example
>>a=1
>>example.add(a,2)
>>6 --> This is correct
>>a
>>1 --> This is not what expect

It returns 6, which is correct However, when I print "a", it still prints 1 instead of 4. How can i modify the pybind11 definition, so that changes done in argument value inside C++ as visible in python

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055

1 Answers1

0

You cannot. Your variable a is a reference to a constant integer.

In this instance you must rebind the reference to the result: a = example.add(a, 2). Alternatively you can wrap the integer in a type you can mutate.

boycy
  • 1,473
  • 12
  • 25
  • how to wrap the integer immutable in a type that is mutable in python? can you give an example? thanks! – shelper Sep 22 '20 at 21:08