4

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?

3
  • 2
    After adding a semicolon in your constructor for Parameter, this test code worked fine for me: pastie.org/873263 Commented Mar 17, 2010 at 3:41
  • 1
    @Goose, The question is about using this code from Python, not from C++. Commented Mar 17, 2010 at 17:50
  • @Barry mhm. This was just a quickly made up example. Commented Mar 18, 2010 at 4:01

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

In my project I solve same issue by creating a smart vector which doesn't copy a data in copy-ctor, but share a pointer to data.
Thank you!! I helps, but I thought python managed everything with references?
May be I'm wrong but python references like c++ pointers, not references.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.