SWIG and char* newb questions :)

Heiko Wundram modelnine at modelnine.org
Tue Jul 29 07:13:23 EDT 2008


Am Dienstag, 29. Juli 2008 12:51:36 schrieb code_berzerker:
> Ok now more seriously. I have question refering to char* used as
> function parameters to return values. I have read SWIG manual to find
> best way to overcome that, but there are many warnings about memory
> leaks and stuff, so I feel confused.
>
> Ok to put it more simply: how to safely define a variable in Python
> and have it modified by C/C++ function?

At least for strings, this won't work. Python strings are immutable (and 
Python optimizes some things based on this knowledge), and as such you can 
pass a Python string(-object) into a C/C++ function and retrieve its value 
there as a const (!) char* using the PyString_*-API (I have no idea how this 
is encapsulated in SWIG), but cannot/should not modify it (a const_cast<> is 
almost always a sign of bad programming, anyway).

The only real choice you have is to have your wrapper return a new string 
object, created using one of the PyString_FromString[AndSize] functions. 
Check the Python C-API documentation for more info on this.

Anyway, on a different note, I personally have always found it simpler to not 
use SWIG to generate C extensions for Python, but to use the Python C-API 
directly.

Hope this helps!

-- 
Heiko Wundram



More information about the Python-list mailing list