Cython应在需要时自动将C++ set转换为Python set,但是如果您确实需要在C++对象上使用迭代器,也可以这样做。
如果我们创建一个非常简单的示例,在其中构造一个C++集合:
libset.cc
#include <set>
std::set<int> make_set()
{
return {1,2,3,4};
}
libset.h
#include <set>
std::set<int> make_set();
我们可以编写Cython包装器来调用此代码。下面是一个示例,展示了如何以Pythonic的方式迭代集合(在后台使用C++迭代器),以及如何直接使用迭代器。
pyset.pyx
from libcpp.set cimport set
from cython.operator cimport dereference as deref, preincrement as inc
cdef extern from "libset.h":
cdef set[int] _make_set "make_set"()
def make_set():
cdef set[int] cpp_set = _make_set()
for i in cpp_set:
print i
cdef set[int].iterator it = cpp_set.begin()
while it != cpp_set.end():
print deref(it)
inc(it)
return cpp_set
这样就可以使用简单的setup.py进行编译。
setup.py
from distutils.core import setup, Extension
from Cython.Build import cythonize
setup( ext_modules = cythonize(Extension(
"pyset",
sources=["pyset.pyx", "libset.cc"],
extra_compile_args=["-std=c++11"],
language="c++"
)))