如何在Cython中使用C ++ operator []?

时间:2013-03-19 17:21:28

标签: c++ python cython

我需要包装一个定义operator []的C ++类FooContainer:

//foo.h:
#include <vector>
using namespace std;

struct Foo
{
  Foo()
    : value(42) {};
  int value;   
};


class FooContainer
{
public:
    FooContainer() { this->values = vector<Foo> (100) ;}
    Foo operator[](int i) {return values[i];}; // <-- the function I need to call

private:
  vector<Foo> values;    

};

我试图编写相应的.pyx文件,但无论我尝试什么,我都无法弄清楚如何使用Foo :: operator

from cython.operator cimport dereference as deref


cdef extern from "foo.h":
   cdef cppclass CppFoo "Foo":
     pass

cdef extern from "foo.h":
   cdef cppclass CppFooContainer "FooContainer":
     FooContainer()
     Foo operator[](int)


cdef class Foo:
    cdef CppFoo * thisptr

cdef class FooContainer:
    cdef CppFooContainer* thisptr

    def __cinit__(self):
       self.thisptr = new CppFooContainer ()

    def __dealloc__(self):
       if self.thisptr:
           del self.thisptr
           self.thisptr = <CppFooContainer*> 0

    def __getitem__(self, int i):
       cdef CppFoo f  = deref(self.thisptr)[i]  #just one out of many try

我可能错过了一些简单的解决方案,但我总是最终得到错误:&#34;无法将Python对象转换为&#39; CppFoo&#39;&#34;。使用运算符[]的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

operator[]的用法是正确的(Cython不需要数组索引操作符的特殊语法),但是

cdef extern from "foo.h":
   cdef cppclass CppFooContainer "FooContainer":
     FooContainer()
     Foo operator[](int)

应该是:

cdef extern from "foo.h":
   cdef cppclass CppFooContainer "FooContainer":
     CppFooContainer()
     CppFoo operator[](int)

因为FooContainerFoo引用了之后声明的Python扩展类类型,而不是“foo.h”中的C ++类类型。