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

3 投票
1 回答
1333 浏览
提问于 2025-04-17 19:39

我需要把一个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

我可能错过了简单的解决办法,但我总是遇到这个错误:“无法将Python对象转换为'CppFoo'”。使用操作符[]的正确方法是什么呢?

1 个回答

3

使用 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++ 类类型。

撰写回答