[C++-sig] Passing std::wstring to Python callback
Giuseppe Corbelli
giuseppe.corbelli at copanitalia.com
Fri Apr 3 10:16:56 CEST 2015
On 18/03/2015 22:25, Bogdan Cristea wrote:
>
> Hi
>
> I am using boost python for providing python bindings for a C++ library. I am
> using Python 2.7. My library needs to call callbacks that are defined in
> Python. There callbacks can take a string parameter. C++ side I am always
> using std::wstring. Everything works on as long as std::wstring contains only
> ASCII chars, but once I get something like “é” my application crashes. This
> issue seems to be related to the way I pass std::wstring to Python callbacks:
> as long as I make sure that the passed string has only ASCII chars it is ok.
> My problem is how do I pass unicode strings to Python.
Late reply, I know...
Have a look at boost/python/converter/builtin_converters.hpp
You should find something like
#if defined(Py_USING_UNICODE) && !defined(BOOST_NO_STD_WSTRING)
BOOST_PYTHON_TO_PYTHON_BY_VALUE(std::wstring,
::PyUnicode_FromWideChar(x.data(),implicit_cast<ssize_t>(x.size())),
&PyUnicode_Type)
# endif
PyUnicode_FromWideChar returns NULL on failure, so a SEGV may as well be expected.
AFAIK an UTF16 encoding should be OK.
--
Giuseppe Corbelli
WASP Software Engineer, Copan Italia S.p.A
Phone: +390303666318 Fax: +390302659932
E-mail: giuseppe.corbelli at copanitalia.com
More information about the Cplusplus-sig
mailing list