0

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.

Ryan Ginstrom
  • 13,915
  • 5
  • 45
  • 60
Thun
  • 51
  • 2

1 Answers1

2

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.

Craig McQueen
  • 41,871
  • 30
  • 130
  • 181
Duncan
  • 92,073
  • 11
  • 122
  • 156
  • 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 May 17 '10 at 12:14