Cython PXD似乎并没有用于PYX文件

Cython PXD does not seem to be used for PYX file

本文关键字:用于 PYX 文件 并没有 PXD Cython      更新时间:2023-10-16

我正试图通过实现从C++到Python的线性插值器来学习cython。我正在尝试将PXD头文件用于最终的Integrator对象,这样它就可以在以后的其他方法/类中重用,所以我希望PXD头可以使用。

我有一个cpp_linear_interpolation.cpp和cpp_linear _interpolation.h,它们运行良好,插值器以两个双(x和y(向量作为输入进行实例化。

有我的文件

cy_linear_interpolation.pxd

# distutils: language = c++
import cython
import numpy as np
cimport numpy as np
from libcpp.vector cimport vector
cdef extern from "cpp_linear_interpolation.h":
    cdef cppclass cppLinearInterpolation:
        cppLinearInterpolation(vector[double], vector[double]) except +
        vector[double] interp(vector[double]) except +
        vector[double] m_x
        vector[double] m_y
        int m_len
        double m_x_min
        double m_x_max

py_linear_interpolation.pxd

from cy_linear_interpolation cimport cppLinearInterpolation
cdef class LinearInterpolation:
     cdef cppLinearInterpolation * thisptr

py_linear_interpolation.pyx

import cython
import numpy as np
cimport numpy as np
from libcpp.vector cimport vector
from cy_linear_interpolation cimport cppLinearInterpolation

cdef class LinearInterpolation:
    # cdef cppLinearInterpolation *thisptr
    def __cinit__(self,vector[double] x,vector[double] y):
        self.thisptr = new cppLinearInterpolation(x, y)
    def __dealloc__(self):
        del self.thisptr
    def interpolate(self,vector[double] x_new):
        return self.thisptr.interp(x_new)

设置.py

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy

setup( name = 'Cython_LinInt',
       ext_modules=[Extension("cython_linear_interpolation",
                              sources=["py_linear_interpolation.pyx", "cpp_linear_interpolation.cpp",],
                              language="c++",
                              include_dirs=[numpy.get_include()]) 
       ],
       cmdclass = {'build_ext': build_ext},
)    

使用Microsoft(R(C/C++优化编译器15.00.30729.01版x64 进行编译

我收到错误信息

无法将"cppLinearInterpolation*"转换为Python对象

如果我移动

cdef cppLinearInterpolation * _thisptr

到pyx文件(py_linear_interpolation.pyx中注释掉的行(,它编译并运行,但随后我无法从另一个cython文件访问指针。理想情况下,我可以从python实例化插值器,并将其用作其他python/cython函数的参数。我确信我一定在做一些愚蠢的事情,但我在这个问题上被阻止了一段时间,还没有找到解决方案。。。

编辑:py_linear_interpolation.pyx中有一个拼写错误,现已更正EDIT 2:py_linear_interpolation.pyd中有相同的类型,成员名称为thisptr,代码仍然没有编译,我得到了相同的错误。cython编译器似乎没有识别self.thisptr不是python对象,应该是指向cppLinearInterpolation 的指针

更改此项:

self.thisptr = new cppLinearInterpolation(x, y)

收件人:

self._thisptr = new cppLinearInterpolation(x, y)

我会尝试将__cinit__更改为

def __init__(self, x, y):
    self.thisptr = new cppLinearInterpolation(x, y)

由于没有提供cpp_linear_interpolation.h和其他文件,我无法自己测试。