gpt4 book ai didi

python - 指针和 "Storing unsafe C derivative of temporary Python reference"

转载 作者:太空狗 更新时间:2023-10-29 20:15:25 27 4
gpt4 key购买 nike

我正在编写代码以将(可能)非常大的整数值存储到指针引用的 chars 数组中。我的代码如下所示:

cdef class Variable:

cdef unsigned int Length
cdef char * Array

def __cinit__(self, var, length):
self.Length = length
self.Array = <char *>malloc(self.Length * sizeof(char)) # Error
for i in range(self.Length):
self.Array[i] = <char>(var >> (8 * i))

def __dealloc__(self):
self.Array = NULL

当我尝试编译代码时,我在注释行收到错误“Storing unsafe C derivative of temporary Python reference”。我的问题是:我在 C 中派生并存储了哪个临时 Python 引用,我该如何修复它?

最佳答案

问题在于,在将数组赋值给 self.Array 之前,正在创建一个临时变量来保存数组,一旦方法退出,它就不再有效。

请注意 documentation建议:

the C-API functions for allocating memory on the Python heap are generally preferred over the low-level C functions above as the memory they provide is actually accounted for in Python’s internal memory management system. They also have special optimisations for smaller memory blocks, which speeds up their allocation by avoiding costly operating system calls.

因此,您可以编写如下,这似乎按预期处理了这个用例:

from cpython.mem cimport PyMem_Malloc, PyMem_Realloc, PyMem_Free

cdef class Variable:

cdef unsigned int Length
cdef char * Array

def __cinit__(self, var,size_t length):
self.Length = length
self.Array = <char *>PyMem_Malloc(length * sizeof(char))
#as in docs, a good practice
if not self.Array:
raise MemoryError()

for i in range(self.Length):
self.Array[i] = <char>(var >> (8 * i))

def __dealloc__(self):
PyMem_Free(self.Array)

关于python - 指针和 "Storing unsafe C derivative of temporary Python reference",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32371919/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com