[C++-sig] Calling a C++ function with arguments by reference (lvalues)

Nat Goodspeed nat at lindenlab.com
Mon Aug 2 23:35:24 CEST 2010


Oded Padon wrote:

> There is another reason why I think this has to be possible.
 > It is possible using ctypes. Using ctypes with the same C++
 > code written above (except for extern "C"), the following python code:
> 
> import ctypes;
> lib_cpp = ctypes.CDLL('./test_cpp.so')
> result = ctypes.c_int(0);
> lib_cpp.add(1, 2, ctypes.byref(result));
> print result;
> 
> prints: "c_long(3)"

Yes. In this case, you allocated and passed a specific ctypes object 
guaranteed to be compatible with a C++ int.

I still stand by my earlier point. Python doesn't recognize the concept 
of 'const'. All int values are equally immutable. If Boost.Python were 
to allow usage like this:

result = int()
cppmodule.add(1, 2, result)
assert result == 3

then what should happen in this innocent-looking case?

result = int()
cppmodule.add(result, 1, 2)

Or consider this. In recent versions of the Python interpreter, if you 
assign (say) 5 to a variable and then double it enough times, you will 
eventually produce a value larger than a C++ int. Unlike C++, Python 
will grow the storage associated with that variable to be able to 
represent the value exactly.

What should happen when you try to pass *that* value to a C++ int& 
parameter?

If you're happy with the ctypes approach, you could easily introduce a 
convention like this:

class RefInt(object):
     def __init__(self, value=int()):
         self.value = value

     def __int__(self):
         return self.value

     # ...other operations as desired for convenience...

Now, assuming you've coded your C++ add() function to accept a RefInt, 
you can write:

result = RefInt(0)
cppmodule.add(1, 2, result)
assert int(result) == 3

which is just as facile as the ctypes code you cited.


More information about the Cplusplus-sig mailing list