Cython重载"找不到合适的方法"

时间:2015-03-20 16:11:37

标签: python python-2.7 constructor override cython

我无法通过Cython访问C ++类中的重载构造函数。我正在尝试按照here描述包装C ++类。该类有多个构造函数,它们具有相同数量的参数,仅按类型不同,例如提到的类here。但是,Cython无法决定调用哪个构造函数,给出错误"找不到合适的方法"。

例如,给定foo.h如下

class Foo 
{
    public:
        int which_constructor;

        Foo(int){ which_constructor = 1; }
        Foo(bool){ which_constructor = 2; };

        ~Foo();
};

和pyfoo.pyx如下

from libcpp cimport bool as bool_t

cdef extern from "foo.h":
    cdef cppclass Foo:
        Foo(int)
        Foo(bool_t)
        int which_constructor

cdef class PyFoo:
    cdef Foo *thisptr      # hold a C++ instance which we're wrapping

    def __cinit__( self, *args, **kwargs):
        # get list of arg types to distinquish overloading
        args_types = []
        for arg in args:
            args_types.append(type(arg))

        if (args_types == [int]):
            self.thisptr = new Foo(args[0])
        elif (args_types == [bool]):
            self.thisptr = new Foo(args[0])
        else:
            pass

    def which_constructor(self):
        return self.thisptr.which_constructor

和设置文件setup_pyfoo.py如下

from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize

setup(
    ext_modules = cythonize(
        Extension("pyfoo", ["pyfoo.pyx"],
            language="c++",
        )
    )
)

当我尝试编译时,出现以下错误

C:\Users\bennett.OCM\Documents\Python\Cython>python setup_pyfoo.py build_ext --i
nplace
Compiling pyfoo.pyx because it changed.
Cythonizing pyfoo.pyx

Error compiling Cython file:
------------------------------------------------------------
...
        for arg in args:
            args_types.append(type(arg))

        # four differnent constructors.
        if (args_types == [int]):
            self.thisptr = new Foo(args[0])
                                 ^
------------------------------------------------------------

pyfoo.pyx:20:34: no suitable method found

Error compiling Cython file:
------------------------------------------------------------
...

        # four differnent constructors.
        if (args_types == [int]):
            self.thisptr = new Foo(args[0])
        elif (args_types == [bool]):
            self.thisptr = new Foo(args[0])
                                 ^
------------------------------------------------------------

pyfoo.pyx:22:34: no suitable method found

如果我删除了pyfoo.pyx中的一个或另一个构造函数定义,那么事情就会正常工作,即使foo.h中仍然存在多个构造函数。我怀疑Cython需要被强制调用一个特定的构造函数。我只是不知道如何帮助它。任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:2)

您可以明确地转换参数:

if (args_types == [int]):
    self.thisptr = new Foo(<int> args[0])
elif (args_types == [bool]):
    self.thisptr = new Foo(<bool_t> args[0])
else:
    pass

请务必投放到<bool_t>而不是<bool>,否则会导致模糊的重载错误。