如果它有所作为,我对有关 Python 3 的答案很感兴趣。
文档声明(here 和 here)PyBuffer_Release() 应该在 PyArg_Parse*() 之后调用 s*, y*.
没有关于 Py_BuildValue() 的文章。这是一个疏忽,还是在 Py_BuildValue() 的情况下,简单的 Py_DECREF() 就足够了?
这是我的具体案例:
uint8_t buf = (uint8_t *)malloc(bufSize);
PyObject *pyBuf = Py_BuildValue("y#", (char *)buf, bufSize);
free(buf);
// do something with pyBuf
// maybe a PyBuffer_Release(get_underlying_buffer(pyBuf)) here?
Py_DECREF(pyBuf);
请您参考如下方法:
我认为不是:
在
PyArg_Parse*和Py_BuildValue函数中,y#指的是字符串和长度,而不是缓冲区,因此没有要释放的底层缓冲区对象。Py_BuildValue的文档说:When memory buffers are passed as parameters to supply data to build objects, as for the s and s# formats, the required data is copied. Buffers provided by the caller are never referenced by the objects created by Py_BuildValue().
锁定
PyArg_Parse*使用的缓冲区的目的是,您已经引用 Python 的一些数据到 C,并且您想在 C 中处理它,而不希望它被 Python 修改。在这种情况下,您已将一些数据从 C 语言复制到 Python 中,因此无需保护原始数据免遭修改。
