如何在Cython包装的C ++类中修复AttributeError?

时间:2019-04-11 18:43:35

标签: c++ class cython wrapper

我想用Cython包装一个C ++类,并为用Python编写的类添加一些功能。编译并导入Python会话即可。但是,当我尝试创建该类的对象时,引发了我不理解的AttributeError。我究竟做错了什么?

这是一个最小的示例:

example.pyx

# distutils: language = c++


import numpy as np
from libcpp.vector cimport vector


cdef extern from 'example.h':
    cdef cppclass MapCpp 'Map':
        MapCpp(vector[double] x, vector[double] y)
        double left 'left'(double x)


cdef class Map:
    cdef MapCpp* map

    def __init__(self, x, y):
        self.x, self.y = np.sort((x, y)).astype(float)
        self.map = new MapCpp(self.x, self.y)

    def left(self, x):
        return self.map.left(x)

example.h

#include <cinttypes>
#include <vector>
#include <algorithm>
#include <cmath>


class Map
{
public:
  std::vector<double> xx, yy;

  Map(std::vector<double> xx_, std::vector<double> yy_): xx(xx_), yy(yy_){}
  ~Map() {}

  double left(double x);
};


double Map::left(double x){
  if ((xx.front() <= x) && (x <= xx.back())){
    uint32_t ix = std::lower_bound(xx.begin(), xx.end(), x) - xx.begin();
    return yy[ix];
  } else {
    return std::nan("");
  }
}

setup.py

from distutils.core import setup
from Cython.Build import cythonize


setup(
    ext_modules = cythonize('example.pyx', force=True, annotate=True)
)

在Ipython会话中尝试该类会给我以下错误:

In [1]: import numpy as np                                                                 

In [2]: from example import Map                                                            

In [3]: xx = np.linspace(0, 1, 11)                                                         

In [4]: yy = xx ** 2                                                                       

In [5]: m = Map(xx, yy)                                                                    
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-5-236848d46102> in <module>
----> 1 m = Map(xx, yy)

~/Desktop/scpm/minimal_example/example.pyx in example.Map.__init__()
     16 
     17     def __init__(self, x, y):
---> 18         self.x, self.y = np.sort((x, y)).astype(float)
     19         self.map = new MapCpp(self.x, self.y)
     20 

AttributeError: 'example.Map' object has no attribute 'x'

0 个答案:

没有答案