如何在Cython中使用c++运算符[]
How to use C++ operator[] in 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[]
的用法是正确的(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++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- 如何使用AngelScript注册SFML Vector2运算符
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 布尔比较运算符是如何在C++中工作的
- 重载运算符new[]的行为取决于析构函数
- 如何防止clang格式在流运算符调用之间添加换行符<<