Return python unicode instances from UTF-8 encoded char * using boost.python

I am trying to do something that should be very simple, but I was not very lucky, as from the existing documentation.

For a python 2 project, I'm trying to get the gettext string translated into the list as a unicode instance into python. The return value for gettext () is a UTF-8 encoded char *, which should be fairly simple to convert to python unicode using PyUnicode_FromString. I have a feeling that this is trivial, but I can’t figure out how to do this.

Basd by comments from Ignacio Vazquez-Abrams and Thomas K. I got this work for one line; in this case, you can get around the entire boost.python infrastructure. Here is an example:

        PyObject* PyMyFunc() {
            const char* txt =  BaseClass::MyFunc();
            return PyUnicode_FromString(txt); 
    }       

which is set using the usual def statement:

class_<MyCclass>("MyClass")
    .def("MyFunc", &MyClass::PyMyFunc);

, , unicode. :

boost::python::list PyMyFunc() {
    std::vector<std::string> raw_strings = BaseClass::MyFunc();
    std::vector<std::string>::const_iterator i;
    boost::python::list result;

    for (i=raw_strings.begin(); i!=raw_strings.end(); i++)
        result.append(PyUnicode_FromString(i->c_str()));
    return result;
}

: boost:: python:: list, , PyObject.

+5
1

++ - SIG . :

  • boost:: python:: handle < > ++ PyObject *,
  • use boost:: python:: object ++ , PyObject * () ++ , , - :: python:: list .

:

boost::python::list PyMyFunc() {
    std::vector<std::string> raw_strings = BaseClass::MyFunc();
    std::vector<std::string>::const_iterator i;
    boost::python::list result;

    for (i=raw_strings.begin(); i!=raw_strings.end(); i++)
        result.append(
             boost::python::object(
               boost::python::handle<>(
                 PyUnicode_FromString(i->c_str()))));
    return result;
}
+2

All Articles