Cython PXD似乎不用于PYX文件

时间:2016-03-14 20:41:58

标签: c++ cython

我试图通过实现从C ++到Python的线性插值来学习cython。 我正在尝试将PXD头文件用于最终的Intepolator对象,以便它可以在其他方法/类中重复使用,所以我想让PXD头文件可用。

我有一个cpp_linear_interpolation.cpp和cpp_linear_interpolation.h工作正常,内插器用两个double(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的指针

2 个答案:

答案 0 :(得分:1)

改变这个:

self.thisptr = new cppLinearInterpolation(x, y)

要:

self._thisptr = new cppLinearInterpolation(x, y)

答案 1 :(得分:0)

我会尝试将__cinit__更改为

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

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