Pass by reference in Boost::Python

五迷三道 提交于 2019-12-10 19:36:55

问题


Consider something like:

struct Parameter
{
    int a;
    Parameter(){a = 0;}
    void setA(int newA){a = newA;}
};
struct MyClass
{
    void changeParameter(Parameter &p){ p.setA(-1);}
};

Well, let's fast forward, and imagine I already wrapped those classes, exposing everything to python, and imagine also I instantiate an object of Parameter in the C++ code, which I pass to the python script, and that python script uses a MyClass object to modify the instance of Parameter I created at the beginning in the C++ code.

After that code executes, in C++ Parameter instance is unchanged!!! This means it was passed by value (or something alike :S), not by reference. But I thought I declared it to be passed by reference...

I can't seem to find Boost::Python documentation about passing by reference (although there seems to be enough doc about returning by reference...). Can anyone give some hint or pointer please?


回答1:


Python doesn't have references, so when you pass reference to python boost::python calls copy-ctor of your object.

In this case you have two choices: Replace references with pointers (or smart-pointers) or pass into python your own 'smart-reference' object/wrapper.



来源:https://stackoverflow.com/questions/2459588/pass-by-reference-in-boostpython

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!