On 08/02/2010 01:46 PM, Oded Padon wrote:
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)"
I do prefer however to use boost.python, as I would at a later stage want to
expose C++ classes to python, but exposing functions like the above is step one
for me.
This works because ctypes provides integer types ("c_int", etc.) which
are mutable in Python; in other words, you can change the value of a
ctypes.c_int object.
That isn't true for regular Python int objects (or str objects, or tuple
objects, for instance). Whenever it *looks* like you've changed one, as in:
a = 3
a += 2
... you actually haven't. The second line won't add 2 to the integer
object that previously had the value 3. It might construct a new int
object with a value of 5. And in some Python implementations, it might
just increment the reference count of a pre-existing global integer
object that already has the value 5 and set "a" to be a reference to
that object. The point is that immutable types in Python simply cannot
be modified in place, and Python plays tricks to make it *seem* like
they're being modified while it ensures that they never really are.
If you really want to go down this route, you can create a C++ object
that behaves like an int and wrap it with Boost.Python; that object
won't be immutable, and you can give it the necessary operators to
interact properly with regular ints. And you'll be able to pass it
by-value to functions. But my guess is that it's probably much easier
just to pass a dictionary to all of your functions.
Hope that helps!
Jim Bosch
_______________________________________________
Cplusplus-sig mailing list
Cplusplus-sig@python.org
http://mail.python.org/mailman/listinfo/cplusplus-sig