Skip to main content
 首页 » 编程设计

python之在 Py_BuildValue ("y#"之后是否需要 PyBuffer_Release,...)

2024年09月07日28yyy_WW

如果它有所作为,我对有关 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); 

请您参考如下方法:

我认为不是:

  1. 在PyArg_Parse* 和Py_BuildValue 函数中,y# 指的是字符串和长度,而不是缓冲区,因此没有要释放的底层缓冲区对象。

  2. 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 中,因此无需保护原始数据免遭修改。