加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在Cython中迭代C集?

发布时间:2020-12-16 05:35:33 所属栏目:百科 来源:网络整理
导读:我用Cython优化 python代码. C中的一个集合存储了我的所有结果,我不知道如何访问数据以将其移动到 Python对象中.结构必须是一组.我无法将其更改为矢量,列表等. 我知道如何在Python和C中执行此操作,但不是在Cython中.如何在Cython中检索迭代器?我通过libcpp.
我用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

#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: #Iterate through the set as a c++ set
        print i

    #Iterate through the set using c++ iterators.
    cdef set[int].iterator it = cpp_set.begin()
    while it != cpp_set.end():
        print deref(it)
        inc(it)

    return cpp_set    #Automatically convert the c++ set into a python 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++"
     )))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读