如何创建任意大小的结构数组 cython

问题描述 投票:0回答:1

我想知道如何在 Cython 中创建一个结构数组,然后可以填充并进行计算。

示例

这里有 Cython 代码

%%cython 
cimport numpy as cnp
cimport cython


from collections import namedtuple

Couple = namedtuple('Couple', ['female', 'male'], verbose=False)

cdef struct CyCouple:
    int female
    int male


cpdef int np_cy_count_women_earning_more2(list py_couples):

    cdef:
        int count = 0, r, N
        CyCouple cy_couples[100_0000] # THIS IS HARDCODED

    N  = len(py_couples)

    make_CyCouple_array(py_couples, cy_couples, N)

    for n in range(N):
        r = cy_couples[n].female > cy_couples[n].male
        count += r
    return count

我想要一个通用版本,而不是 # THIS IS HARDCODED 中的定义。

我能做什么?

cython
1个回答
0
投票

您可以使用使用标准 C malloc/free 函数的动态内存管理,但您必须严格避免内存泄漏,特别是当您调用一些可能引发 Python 异常的代码时。

在许多情况下,让

array.array
执行分配会更容易。通过在作用域中保留对该对象的引用,您可以控制分配的内存块的生命周期。

我用来做什么:

# Write that once at the top of you file so
# we can leverage the useful array.clone() function later.
from cpython cimport array
cdef array.array byte_array_template = array.array('b', [])

# ...

# When I want to allocate memory
cdef array.array arr = array.clone(byte_array_template, n*sizeof(CyCouple), zero=False)
cdef CyCouple* ptr = <CyCouple*>arr.data.as_chars
# The pointer remains valid as long as you have a Python variable 
# holding a reference to the array.
© www.soinside.com 2019 - 2024. All rights reserved.