python - 如何打印 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?
谢谢。
解决方案
而不是戳实现细节,您应该通过记录的 API,特别是通过PyByteArray_AS_STRING
或PyByteArray_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 *
。
推荐阅读
- javascript - 如何更改范围滑块标记?
- c++ - 是否有一种内置方法可以转换为不同的基础类型但保留 const 限定符?
- java - 如何将泛型作为参数来接收稍后应用特定方法的函数?
- c# - 我如何在 c# 中使用其 URL 调用 Web 服务
- javascript - JS 为动态声明的元素委托唯一事件 (one())
- asp.net-core-mvc - 从剃刀视图 ASP.NET Core 2.1 MVC 中使用 ViewModel 方法
- angular - 无法使用角度材料以角度正确地将数据行从一个表交换到另一个表
- node.js - 节点停止和重启时抛出错误
- r - 如何将顶点属性名称传递给igraph中的函数
- c# - 使用 CSVHelper 反序列化 CSV 时使用特定函数创建对象的新实例