【发布时间】:2016-03-14 20:41:57
【问题描述】:
我正在尝试通过实现从 C++ 到 Python 的线性插值器来学习 cython。 我正在尝试将 PXD 头文件用于最终的 Intepolator 对象,以便它可以在其他方法/类中重用,所以我希望 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)
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 for 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 的指针
【问题讨论】: