我需要包装一个定义运算符 [] 的 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[] 的正确方法?
最佳答案
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)
因为 FooContainer
和 Foo
指的是之后声明的 Python 扩展类类型,而不是来自“foo.h”的 C++ 类类型。
关于c++ - 如何在 Cython 中使用 C++ operator[]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15506284/