无法修改cython中的集合

Cannot modify set in cython

本文关键字:集合 cython 修改      更新时间:2023-10-16

我想在c++中标记一组无符号整数,并在Python:中对其进行修改

%load_ext Cython
%load_ext cythonmagic
%%cython 
# distutils: language = c++
from libcpp.set cimport set as cpp_set
from cython.operator cimport dereference as deref
def modify_test_data():
    cdef (cpp_set[int])* s = new cpp_set[int]()
    print deref(s), type(deref(s))
    deref(s).add(1)
    print deref(s)
modify_test_data()

输出:

set([]) <type 'set'>
set([]) # here i would expect 'set([1])'

我不确定我是否需要deref的东西,但如果没有它,类型就不匹配。有人能解释一下我是如何做到这一点的吗?

AFAICT,您将Python的set与C++的std::set混为一谈。后者的方法是insert,而不是add(与前者一样)。

如果您将相关行更改为:

deref(s).insert(1)

输出变为:

set([]) <type 'set'>
set([1])