[C++-sig] Efficient string passing

Stefan Seefeld seefeld at sympatico.ca
Thu Nov 19 14:56:39 CET 2009


On 11/19/2009 08:30 AM, Mohan Ganesalingam wrote:
>> I believe this is impossible: Python treats strings as immutable, 
>> which means you can't manipulate them in-place, and there is no C API 
>> function 
>
> There is apparently one exception to this, which I was utilising:
> char* PyString_AsString(PyObject *string) Returns a NUL-terminated 
> representation of the contents of string. The pointer refers to the 
> internal buffer of string, not a copy. The data must not be modified 
> in any way, unless the string was just created using 
> PyString_FromStringAndSize(NULL, size).
>
> I.e. if you create a string using PyString_FromStringAndSize(0, n), 
> then you can immediately modify its contents using PyString_AsString. 
> AFAICS this functionality is (reasonably enough) not wrapped by 
> boost::python::str, so you have to use the underlying API.

OK, perhaps I misunderstood your use-case. Indeed, you may allocate a 
string using the Python C API, and have a small window within which you 
can manipulate its content, before handing control back to the Python 
runtime. If that is what you need, great.

For avoidance of doubt: I don't think it would be valid to modify that 
string after you have handed control back to Python. The Python runtime 
may well create hashes from it for efficient lookup, which build on the 
immutability of this type of object.

Regards,
         Stefan

-- 

       ...ich hab' noch einen Koffer in Berlin...



More information about the Cplusplus-sig mailing list