如何在Cython中使用c++运算符[]

How to use C++ operator[] in Cython?

本文关键字:c++ 运算符 Cython      更新时间:2023-10-16

我需要包装一个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'"。使用运算符[]的正确方法是什么?

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