[C++-sig] Converting from Python integer to C++ by reference

Greg Landrum greg.landrum at gmail.com
Thu Aug 18 22:32:13 CEST 2005


On 8/18/05, Saikat Chakrabarti <smartel at real.com> wrote:
> Hello,
>    I am attempting to expose a class in C++ with a method that takes a
> reference to an integer.  Thus, a simple version of what I have is as
> follows:
> 
> class C
> {
> public:
>         void SetMe(int& i);
> }
> 
> and SetMe is implemented as follows:
> 
> void C::SetMe(int& i)
> {
>         i = 5;
> }
> 
> and my goal is to be able to call this method from Python with an
> integer and have the value of that integer in Python set.  Thus, in
> Python, I would like to do:
> 
> c = C()
> i = 0
> c.SetMe(i)
> 
> and have i's value be 5.  However, when I do this, I get an exception on
> line 292 of arg_from_python.hpp (at the end of the constructor for
> reference_arg_from_python) that simply says I have an access violation.
>   If I get rid of the reference and made SetMe simply declared as "void
> SetMe(int i)", the code works fine.  Also, if I change int to long (as I
> believe Python integers are actually C++ long types), but keep the
> reference (thus, having void SetMe(long& i), it gives me the same error.
>   It seems like I am doing something fundamentally wrong.  How should I
> fix this problem?

I believe that the fundamental problem here is that because integers
are not mutable objects in Python, there's no concept of a "reference
to an int" as far as Python is concerned. For example, if you were to
attempt to write your example in Python, you'd get the same behavior:
>>> class C:
...     def SetMe(self,i):
...             i = 5
...
>>> c = C()
>>> i = 0
>>> c.SetMe(i)
>>> i
0

One way to simulate modifying the integer would be to return the
result, something like:

>>> class C:
...     def SetMe(self,i):
...             i = 5
...             return i
...
>>> c = C()
>>> i = 0
>>> i=c.SetMe(i)
>>> i
5

-greg



More information about the Cplusplus-sig mailing list