[C++-sig] automatic conversion from python unicode object to C++ std::string?

Jim Bosch talljimbo at gmail.com
Fri Aug 12 21:15:01 CEST 2011

On 08/12/2011 04:36 AM, John Reid wrote:
> I recently upgraded to ipython 0.11. In 0.11 sys.argv entries are of
> type unicode rather than string. All of my scripts that call into
> boost.python extensions fail as my exposed functions expect arguments of
> type std::string. Presumably I could recode all my functions to use
> std::wstring and everything would work. This would be a lot of work so
> for the moment, I'm encoding everything in python from unicode to
> strings. I was wondering if there is a simple way to tell my
> boost.python extensions to do this encoding automatically.

Hmm. You might be able to write a custom rvalue_from_python conversion 
from the Python unicode type to std::string.  You could only do that 
once, and it would work everywhere, but it would mean unicode objects 
would be convertible to std::string everywhere, and I'm not sure that's 

I don't think the from-python conversions are terribly well-documented, 
but you can learn a lot from 
boost/python/converter/rvalue_from_python_data.hpp.  If you need help, 
just ask.

Good luck!

Jim Bosch

More information about the Cplusplus-sig mailing list