首页 > 解决方案 > Cython promlem:cimport libcpp.vector 未编译

问题描述

我正在尝试使用 cython 来加速我的代码。由于我正在使用字符串数组,因此我想使用 c++ 中的字符串和向量。但是如果我导入 c 库,我会遇到编译问题。例如,我尝试从这里实现一个示例:https ://cython.readthedocs.io/en/latest/src/tutorial/cython_tutorial.html 。所以,我的代码是

from libcpp.vector cimport vector

def primes(unsigned int nb_primes):
    cdef int n, i
    cdef vector[int] p
    p.reserve(nb_primes)  # allocate memory for 'nb_primes' elements.

    n = 2
    while p.size() < nb_primes:  # size() for vectors is similar to len()
        for i in p:
            if n % i == 0:
                break
        else:
            p.push_back(n)  # push_back is similar to append()
        n += 1

    # Vectors are automatically converted to Python
    # lists when converted to Python objects.
    return p

我将此代码保存为“test_char.pyx”。对于编译,我使用它:

from Cython.Build import cythonize
setup(name='test_char',
      ext_modules = cythonize('test_char.pyx')
      )

之后我得到 test_char.c,但我没有得到 test_char.py。如果我将使用此代码(没有 cimport):

def primes(int nb_primes):
    cdef int n, i, len_p
    cdef int p[1000]
    if nb_primes > 1000:
        nb_primes = 1000
    len_p = 0  # The current number of elements in p.
    n = 2
    while len_p < nb_primes:
        # Is n prime?
        for i in p[:len_p]:
            if n % i == 0:
                break

        # If no break occurred in the loop, we have a prime.
        else:
            p[len_p] = n
            len_p += 1
        n += 1

    # Let's return the result in a python list:
    result_as_list  = [prime for prime in p[:len_p]]
    return result_as_list

一切都是对的。那么,PLZ,有什么想法吗?

标签: pythonc++importcython

解决方案


from distutils.extension import Extension
extensions = [
    Extension("test_char", ["test_char.pyx"]
              , language="c++"
              )
]
setup(
    name="test_char",
    ext_modules = cythonize(extensions),
)

它可以解决这个问题


推荐阅读