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

hym*_*oth 6 c++ python cython

我试图用签名包装一个c ++函数

vector < unsigned long > Optimized_Eratosthenes_sieve(unsigned long max)
Run Code Online (Sandbox Code Playgroud)

使用Cython.我有一个包含该函数的文件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
)
Run Code Online (Sandbox Code Playgroud)

在我的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
Run Code Online (Sandbox Code Playgroud)

但我得到这个"无法将'矢量'转换为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
Run Code Online (Sandbox Code Playgroud)

Bas*_*ard 2

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

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