指针和“存储临时Python参考的不安全C派生". [英] Pointers and "Storing unsafe C derivative of temporary Python reference"

查看:234
本文介绍了指针和“存储临时Python参考的不安全C派生".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was writing code to store a (potentially) very large integer value into an array of chars referenced by a pointer. My code looks like this:

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

当我尝试编译代码时,在注释行出现了错误存储临时Python引用的不安全的C派生".我的问题是这样的:我在C语言中存储并存储了哪个临时Python参考,该如何解决?

When I tried compiling the code, I got the error, "Storing unsafe C derivative of temporary Python reference" at the commented line. My question is this: which temporary Python reference am I deriving in C and storing, and how do I fix it?

推荐答案

问题在于,在幕后创建了一个临时变量来保存分配给self.Array的数组,并且一旦该方法无效退出.

The problem is that under the hood a temporary variable is being created to hold the array before the assignment to self.Array and it will not be valid once the method exits.

请注意,文档建议:

用于在Python堆上分配内存的C-API函数通常比上面的低级C函数更受青睐,因为它们提供的内存实际上是在Python的内部内存管理系统中解决的.他们还对较小的内存块进行了特殊优化,从而避免了昂贵的操作系统调用,从而加快了分配速度.

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.

因此,您可以编写如下内容,它似乎可以按预期处理此用例:

Accordingly you can write as below, which seems to handle this use case as intended:

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参考的不安全C派生".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆