简体   繁体   中英

To convert PyBytesObject type to PyUnicodeObject type in python3

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM