我需要包装一个定义 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
我可能错过了简单的解决方案,但我总是以错误告终:“无法将 Python 对象转换为 'CppFoo'”。使用 operator[] 的正确方法是什么?