[C++-sig] Passing C++ objects to Python by reference

Garrick Chin nonexistent.ftp at gmail.com
Mon May 29 23:03:54 CEST 2006


The below class is defined in C++ and exposed in Python:

class A
{
public:
    A()
        :value("unchanged") { }

    void setValue(std::string newValue) { value = newValue; }

    std::string value;
};

The following method is defined in Python:

def changeA(a):
    a.setValue("changed")


When changeA() is passed an object created in Python:

a1 = A()
changeA(a1)
print a1.value    #prints "changed"

the passed in object gets changed, but when the equivalent is done in C++:

A a2;
object changeA = dictionary["changeA"];
changeA(a2)
std::cout << a2 << "\n";    //prints "unchanged"

it appears that the C++ object is passed to Python by value instead of
reference.  Is there a way to specify passing by reference instead of
value to boost::python?



More information about the Cplusplus-sig mailing list