无法将'vector<unsigned long>'转换为Python对象

7 投票
1 回答
2703 浏览
提问于 2025-04-16 13:49

我想用Cython来封装一个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

1 个回答

2

如果你只需要在C++中调用你的函数,那就用 cdef 来声明它,而不是用 def

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

撰写回答