7

c++関数を署名でラップしようとしています

vector < unsigned long > Optimized_Eratosthenes_sieve(unsigned long max)

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
)

私の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
4

1 に答える 1

2

C++ の関数を呼び出すだけでよい場合は、cdef代わりに で宣言しdefます。

一方、Python から呼び出す必要がある場合、関数は Python オブジェクトを返す必要があります。この場合、おそらく整数の Python リストを返すようにします。

于 2011-03-23T21:40:27.690 に答える