首页 > 解决方案 > 如何打印 PyByteArrayObject* 的内容?

问题描述

我正在使用PyArg_ParsetupleY使用格式说明符解析从 python 发送的字节数组。

Y (bytearray) [PyByteArrayObject *]
Requires that the Python object is a bytearray object, without attempting any conversion. 
Raises TypeError if the object is not a bytearray object. 

在 C 代码中,我正在做:

static PyObject* py_write(PyObject* self, PyObject* args)
{
       PyByteArrayObject* obj;
       PyArg_ParseTuple(args, "Y", &obj);

.
.
.

python 脚本正在发送以下数据:

arr = bytearray()
arr.append(0x2)
arr.append(0x0)

如何在 C 中遍历 PyByteArrayObject*?打印 2 和 0?

谢谢。

标签: pythoncpython-3.x

解决方案


而不是戳实现细节,您应该通过记录的 API,特别是通过PyByteArray_AS_STRINGPyByteArray_AsString而不是通过直接结构成员访问来访问数据缓冲区:

char *data = PyByteArray_AS_STRING(bytearray);
Py_ssize_t len = PyByteArray_GET_SIZE(bytearray);

for (Py_ssize_t i = 0; i < len; i++) {
    do_whatever_with(data[i]);
}

请注意,公共 API 中的所有内容都将 bytearray 作为 a PyObject *,而不是 a PyByteArrayObject *


推荐阅读