gpt4 book ai didi

python - 将 C 结构传递给 Cython 并转换为 Python numpy 数组

转载 作者:太空宇宙 更新时间:2023-11-03 21:46:55 25 4
gpt4 key购买 nike

main.h

ifndef MAIN_H
define MAIN_H

ifdef __cplusplus
extern "C" {
endif

typedef struct Pythonout{
int pn;
double *px;
}Pythonout;

struct Pythonout l1tf_main(char *ifile_y, double lambda, int rflag);


ifdef __cplusplus
}
endif

endif /* MAIN_H */

Following is the Cython pyx file using main.h

.pyx

cimport numpy as np

cdef extern from "main.h":
ctypedef struct Pythonout:
int n
double *x
cdef Pythonout l1tf_main(char *ifile_y
,double lambdaval,
int rflag);

cdef class Pyclass:
cdef Pythonout pnx

def __cinit__(self, char *pfilename,
lambdaval, rflag):
self.pnx = l1tf_main(pfilename,
lambdaval, rflag)

@property
def n(self):
return self.pnx.n

@property
def x(self):
cdef np.npy_float64 shape[1]
shape[0] = <np.npy_intp> self.pnx.n
ndarray =
np.PyArray_SimpleNewFromData(1,
&(self.pnx.n),np.NPY_FLOAT64,
<void *> self.pnx.x)
np.PyArray_UpdateFlags(ndarray,
ndarray.flags.num
| np.NPY_OWNDATA)
return ndarray

cpdef filtered_trend(char *pfilename, double
lambdaval, int rflag):
pnx = Pyclass(pfilename, lambdaval, rflag)
return pnx.x

在类里面,我在编译时遇到以下错误:

‘Pythonout {aka struct Pythonout}’ has no member named ‘n’

‘Pythonout {aka struct Pythonout}’ has no member named ‘x’

调用对象值pnx.npnx.x时。

最佳答案

您的代码至少存在两个问题。

  1. 导致编译错误的小问题:在 C 中,您将结构体属性称为 pxpn,而在 Cython 中,您将它们称为 xn。这意味着 Cython 生成的代码与 C header 不匹配。使这些保持一致。

  2. np.PyArray_UpdateFlags(ndarray, 
    ndarray.flags.num
    | np.NPY_OWNDATA)

    这告诉 Numpy 现在拥有 x 中的数据并负责释放它。但是假设您有 Python 代码:

    x1 = PyClassInstance.x
    x2 = PyClassInstance.x

    您现在有两个 Numpy 数组,每个数组都相信拥有相同的数据,并且都将尝试释放它。 (类似地,如果您从不访问x,则pnx.x永远不会被释放)您可能应该做的是让PyClass实例负责释放它的 pnx.x (在 __dealloc__ 函数中)。然后在您的 x 属性中执行以下操作:

    ndarray = PyArray_SimpleNewFromData(...)
    Py_INCREF(self) # SetBaseObject doesn't do this so you must do it manually
    PyArray_SetBaseObject(ndarray, self) # check return value for errors...

    现在,Numpy 数组将 PyClass 实例视为拥有数据。

关于python - 将 C 结构传递给 Cython 并转换为 Python numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52433074/

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