在python3中将PyBytesObject类型转换为PyUnicodeObject类型

发布于 2024-09-02 00:18:34 字数 237 浏览 2 评论 0原文

如何将 pyunicodeobject 类型转换为 pybytesobject 类型?

示例:

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

PyUnicodeObject* Uniobj;

function((PyBytesObject*) Uniobj);

结果出现总线错误。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

丢了幸福的猪 2024-09-09 00:18:34

您需要对其进行编码,就像在 Python 中进行编码一样。对于 utf-8 使用:

PyObject* PyUnicode_AsUTF8String(PyObject *unicode)

返回值:新引用。
使用 UTF-8 对 Unicode 对象进行编码,并将结果作为 Python 字节对象返回。错误处理是“严格的”。如果编解码器引发异常,则返回 NULL。

或者,如果您想要 utf-16 或其他编码格式,也有适用于这些的 api。请参阅文档 http://docs.python.org/py3k/c- api/unicode.html(搜索以 PyUnicode_As 开头的函数)。

进行编码时不要忘记检查返回码,并在完成编码后释放对 bytes 对象的引用。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文