无法修改 cython 中的集合

Cannot modify set in cython

我想在c++中decalare一组unsigned ints,并在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 东西,但没有它,类型不匹配。有人可以解释我如何以 clean/elegant 的方式做到这一点吗?

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

如果将相关行更改为:

deref(s).insert(1)

输出变为:

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