[C++-sig] Fill a python::str with contents of a vector<unsigned char>

Imran Fanaswala imran.fanaswala at gmail.com
Mon Jun 7 19:07:32 CEST 2010


> On 06/06/2010 06:51 PM, Embhi Karuche wrote:
>> I have a vector<unsigned char>  whose contents I would like to copy
>> into a python::str.
>> Currently, I am doing:
>>
>> string temp(myvector.begin(), myvector.end());
>> python::str data(temp);
>
> You'll need to use the regular Python C API to avoid the temporary:
>
>
> python::str data(
>   python::handle<>(
>      PyString_FromStringAndSize(&myvector.front(), myvector.size())
>   )
> );

This works:
python::str stuff(reinterpret_cast<const char *>(&foo_vector.front()),
foo_vector.size()*sizeof(FooVector::value_type));

btw, the sizeof(FooVector::value_type) part is not necessary since its
a vector<unsigned char> ; nonetheless, it clearer and possibly robust.


More information about the Cplusplus-sig mailing list