开发者

To convert PyBytesObject type to PyUnicodeObject type in python3

开发者 https://www.devze.com 2022-12-30 07:23 出处:网络
How to convert pyunicodeobject type to pybytesobject type? Example: function(PyBytesObject* byteobj){ ....operation..

How to convert pyunicodeobject type to pybytesobject type?

Example:

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

PyUnicodeObject开发者_StackOverflow* 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号