views:

25

answers:

1

How to convert pyunicodeobject type to pybytesobject type?

Example:

function(PyBytesObject* byteobj){
....operation..
}

PyUnicodeObject* Uniobj;

function((PyBytesObject*) Uniobj);

got a bus error as a result.

+2  A: 

You need to encode it just as you would if you were doing it in Python. For utf-8 use:

PyObject* PyUnicode_AsUTF8String(PyObject *unicode)

Return value: New reference.
Encode a Unicode object using UTF-8 and return the result as Python bytes object. Error handling is “strict”. Return NULL if an exception was raised by the codec.

Or if you want it in utf-16 or some other encoding there are api's for those too. See the docs at http://docs.python.org/py3k/c-api/unicode.html (search for functions beginning with PyUnicode_As).

Don't forget to check the return code when you do the encoding, and release the reference to the bytes object when you're done with it.

Duncan
+1. You beat me to it. :)
Mark Dickinson
Hmm. `PyUnicode_As*` (which takes a unicode `PyObject *`) is a better fit here than `PyUnicode_Encode*`, which takes a `Py_UNICODE *`. I'll delete my answer!
Mark Dickinson