Raise python method calls with reference arguments

I am trying to make a simple call by reference from python to a C ++ class method.

My C ++ code looks like this:

class Foo { protected: int _internalVal; public: Foo() : _internalVal(5){} void getVal(int& val_io) {val_io = _internalVal;} void getValDoesNothing(int val_io) {val_io = _internalVal;} } 

My wrapper code that compiles in order:

 BOOST_PYTHON_MODULE(libBar) { boost::python::class_<Foo>("Foo") .def("getVal", &Foo::getVal) .def("getValDoesNothing", &Foo::getValDoesNothing); } 

However, when I make the following python calls:

 In [1]: import libBar In [2]: f = libBar.Foo() In [3]: f Out[3]: <libBar.Foo at 0x2b483c0> In [4]: val = int() In [5]: #next command is just to check function signature type In [6]: f.getValDoesNothing(val) In [7]: f.getVal(val) --------------------------------------------------------------------------- ArgumentError Traceback (most recent call last) <ipython-input-5-531e4cea97c2> in <module>() ----> 1 f.getVal(val) ArgumentError: Python argument types in Foo.getVal(Foo, int) did not match C++ signature: getVal(Foo {lvalue}, int {lvalue}) 

I work with a library that I do not control, so changing getVal to return a value is not an option.

Is there a way to get the latest Python command to work?

I’ll even take a fix that does not change the Python variable, but still allows you to call a function call.

+6
source share
2 answers

What you are trying to achieve is not valid in Python. Integers are immutable, so you cannot just call a function and hope that it changes its contents.

Since you are working with a library that you do not control and do not change getVal to return a value, this is not an option, you can create a shell like this:

 int getVal(Foo &foo) { int val_io; foo.getVal(val_io); return val_io; }; BOOST_PYTHON_MODULE(libBar) { boost::python::def("getVal", getVal); ... } 

and then use as follows:

 In [1]: import libBar In [2]: f = libBar.Foo() In [3]: f Out[3]: <libBar.Foo at 0x2b483c0 In [3]: libBar.getVal(f) Out[3]: 5 
+5
source

In getValDoesNothing you pass in int. In getVal, you pass a reference to int.

I believe this is the source of your problem.

-1
source

All Articles