如何在Cython中迭代C集?

前端之家收集整理的这篇文章主要介绍了如何在Cython中迭代C集?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我用Cython优化 python代码. C中的一个集合存储了我的所有结果,我不知道如何访问数据以将其移动到 Python对象中.结构必须是一组.我无法将其更改为矢量,列表等.

我知道如何在Python和C中执行此操作,但不是在Cython中.如何在Cython中检索迭代器?我通过libcpp.STLContainer获取STL容器,如

from libcpp.vector cimport vector

但是,我不知道迭代器在Cython中是如何工作的.我需要导入什么?并且,使用迭代器的语法与它们在C中的工作方式相比是否有任何变化?

解决方法

Cython应该在需要时自动将c set转换为python set,但是如果你真的需要在c对象上使用迭代器,你也可以这样做.

如果我们做一个非常简单的例子,我们在c中构造一个集合

libset.cc

  1. #include <set>
  2.  
  3. std::set<int> make_set()
  4. {
  5. return {1,2,3,4};
  6. }

libset.h

  1. #include <set>
  2.  
  3. std::set<int> make_set();

然后我们可以为这段代码编写cython包装器,其中我给出了一个如何以一种漂亮的pythonic方式(在后台使用c迭代器)迭代集合的示例以及如何直接执行它的示例用迭代器.

pyset.pyx

  1. from libcpp.set cimport set
  2. from cython.operator cimport dereference as deref,preincrement as inc
  3.  
  4. cdef extern from "libset.h":
  5. cdef set[int] _make_set "make_set"()
  6.  
  7. def make_set():
  8. cdef set[int] cpp_set = _make_set()
  9.  
  10. for i in cpp_set: #Iterate through the set as a c++ set
  11. print i
  12.  
  13. #Iterate through the set using c++ iterators.
  14. cdef set[int].iterator it = cpp_set.begin()
  15. while it != cpp_set.end():
  16. print deref(it)
  17. inc(it)
  18.  
  19. return cpp_set #Automatically convert the c++ set into a python set

然后可以使用简单的setup.py编译它

setup.py

  1. from distutils.core import setup,Extension
  2. from Cython.Build import cythonize
  3.  
  4. setup( ext_modules = cythonize(Extension(
  5. "pyset",sources=["pyset.pyx","libset.cc"],extra_compile_args=["-std=c++11"],language="c++"
  6. )))

猜你在找的C&C++相关文章