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

标签 c++ python cython

我需要包装一个定义运算符 [] 的 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)

因为 FooContainerFoo 指的是之后声明的 Python 扩展类类型,而不是来自“foo.h”的 C++ 类类型。

关于c++ - 如何在 Cython 中使用 C++ operator[]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15506284/

相关文章:

python - 在 python 中使用 'finally' 子句的范围是什么?

Cython:维度不是 'tagPyArrayObject' 的成员

python - 加快Python时间戳到日期时间的转换

python - 使用 cython 并行化 python 循环 numpy.searchsorted

c++ - 如何将 lambda (c++11) 传递给模板函数?

c++ - 动态数组和普通数组的区别

python - 无法使用 Selenium find_element_by_partial_link_text 找到元素

c++ - 读取二进制文件

c++ - 在函数 Qt C++ 中使用 UI 数组

python - [...] 是什么意思作为 python 中的输出?