我想通过实现从C++到Python的线性插值器来学习cython。 我想为最终的Intepolator对象使用PXD头文件,以便它可以在其他方法/类下重用,所以我想让PXD头文件可用。Cython PXD似乎不用于PYX文件
我有一个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)
setup.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中存在一个错误,现在更正 编辑2:相同的类型是在py_linear_interpolation.pyd中,成员名称是thisptr,代码仍然没有编译,我得到相同的错误。它似乎并不该用Cython编译器识别出self.thisptr不是一个Python的对象,应该是一个指向cppLinearInterpolation
谢谢你的答案Czarek。这是我的一种类型,代码仍然没有正确的thisptr名称 – Damien022
@ Damien022更新回答 –
与最新的变化,我现在得到py_linear_interpolation.pyx:12:5:C类'LinearInterlation'被声明,但没有定义为 – Damien022