gpt4 book ai didi

c++ - 无法将 'vector' 转换为 Python 对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:44:33 24 4
gpt4 key购买 nike

我正在尝试用签名包装一个 C++ 函数

vector < unsigned long > Optimized_Eratosthenes_sieve(unsigned long max)

使用赛通。我有一个包含函数的文件 sieve.h,一个静态库 sieve.a 和我的 setup.py 如下:

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

ext_modules = [Extension("sieve",
["sieve.pyx"],
language='c++',
extra_objects=["sieve.a"],
)]

setup(
name = 'sieve',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules
)

在我的 sieve.pyx 中,我正在尝试:

from libcpp.vector cimport vector

cdef extern from "sieve.h":
vector[unsigned long] Optimized_Eratosthenes_sieve(unsigned long max)

def OES(unsigned long a):
return Optimized_Eratosthenes_sieve(a) # this is were the error occurs

但我收到此“无法将‘ vector ’转换为 Python 对象”错误。我错过了什么吗?

解决方案:我必须从我的 OES 函数返回一个 python 对象:

def OES(unsigned long a):
cdef vector[unsigned long] aa
cdef int N
b = []
aa = Optimized_Eratosthenes_sieve(a)
N=aa.size()
for i in range(N):
b.append(aa[i]) # creates the list from the vector
return b

最佳答案

如果您只需要为 C++ 调用函数,请使用 cdef 而不是 def 声明它。

另一方面,如果您需要从 Python 调用它,您的函数必须返回一个 Python 对象。在这种情况下,您可能会让它返回一个 Python 整数列表。

关于c++ - 无法将 'vector<unsigned long>' 转换为 Python 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5327894/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com