Python 如何打印PyByteArrayObject*的内容?
我使用Y格式说明符解析python发送的bytearrayPython 如何打印PyByteArrayObject*的内容?,python,c,python-3.x,Python,C,Python 3.x,我使用Y格式说明符解析python发送的bytearray 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_w
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吗
谢谢。在评论部分的帮助下,我找到了PyByteArrayObject的
/* Object layout */
typedef struct {
PyObject_VAR_HEAD
Py_ssize_t ob_alloc; /* How many bytes allocated in ob_bytes */
char *ob_bytes; /* Physical backing buffer */
char *ob_start; /* Logical start inside ob_bytes */
Py_ssize_t ob_exports; /* How many buffer exports */
} PyByteArrayObject;
以及循环的实际代码
PyByteArrayObject* obj;
PyArg_ParseTuple(args, "Y", &obj);
Py_ssize_t i = 0;
for (i = 0; i < PyByteArray_GET_SIZE(obj); i++)
printf("%u\n", obj->ob_bytes[i]);
我得到了预期的输出
更好的是,只需使用
您不应该刺探实现细节,而应该通过PyByteArray_AS_STRING或PyByteArray_AsString而不是通过直接结构成员访问来访问数据缓冲区: char*data=PyByteArray\u AS\u STRINGbytearray; Py_ssize_t len=PyByteArray_GET_size字节数组; 对于Py_ssize_t i=0;i
char* s = PyByteArray_AsString(obj);
int i = 0;
for (i = 0; i < PyByteArray_GET_SIZE(obj); i++)
printf("%u\n", s[i]);