我正在尝试通过实现从 C++ 到 Python 的线性插值器来学习 cython。我正在尝试将 PXD 头文件用于最终的 Intepolator 对象,以便可以在其他方法/类中重用它,因此我希望 PXD 头文件可用。
我有一个 cpp_线性_插值.cpp 和 cpp_线性_插值.h 工作正常,插值器使用两个双精度向量(x 和 y)作为输入进行实例化。
有我的文件
cy_线性_插值.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
Run Code Online (Sandbox Code Playgroud)
py_线性插值.pxd
from cy_linear_interpolation cimport cppLinearInterpolation
cdef class LinearInterpolation:
cdef cppLinearInterpolation * thisptr
Run Code Online (Sandbox Code Playgroud)
py_线性插值.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)
Run Code Online (Sandbox Code Playgroud)
安装程序.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},
)
Run Code Online (Sandbox Code Playgroud)
使用适用于 x64 的 Microsoft (R) C/C++ 优化编译器版本 15.00.30729.01 进行编译
我收到错误消息
无法将“cppLinearInterpolation *”转换为Python对象
如果我搬家
cdef cppLinearInterpolation * _thisptr
Run Code Online (Sandbox Code Playgroud)
到 pyx 文件(py_linear_interpolation.pyx 中注释掉的行),它编译并运行,但随后我无法从另一个 cython 文件访问指针。理想情况下,我能够从 python 实例化插值器,并将其用作其他 python / cython 函数的参数。我确信我一定做了一些愚蠢的事情,但我已经在这个问题上受阻有一段时间了,还没有找到解决方案......
编辑: py_linear_interpolation.pyx 中有一个拼写错误,现已更正编辑 2: py_linear_interpolation.pyd 中有相同的类型,成员名称是 thisptr,代码仍然无法编译,我得到相同的错误。cython 编译器似乎没有识别 self.thisptr 不是 python 对象,应该是指向 cppLinearInterpolation 的指针
改变这个:
self.thisptr = new cppLinearInterpolation(x, y)
Run Code Online (Sandbox Code Playgroud)
到:
self._thisptr = new cppLinearInterpolation(x, y)
Run Code Online (Sandbox Code Playgroud)