python - 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,有什么想法吗?
解决方案
from distutils.extension import Extension
extensions = [
Extension("test_char", ["test_char.pyx"]
, language="c++"
)
]
setup(
name="test_char",
ext_modules = cythonize(extensions),
)
它可以解决这个问题
推荐阅读
- phaser-framework - 移相秒表
- c# - C#: Deconstruct(...) 是否在编译输出中生成额外的垃圾分配?
- python - is_array 函数 php 到 Python
- ruby - 如何使用 Sequel 运行 Postgres psql“斜线”命令
- r - 在闪亮仪表板标题上放置一个下拉按钮以选择主题
- circleci - CircleCI 保持步骤
- angular - 尝试对角度数据表进行排序,但单击排序时没有任何反应
- java - RabbitMQ Java 客户端通道在创建时关闭
- gradle - 自定义 gradle 插件抛出 Unable to load class 'io.github.classgraph.ClassGraph'
- flutter - Flutter 布局 -3 列