Cython 重载 "no suitable method found"

Cython overloading "no suitable method found"

我在通过 Cython 访问 C++ class 中的重载构造函数时遇到问题。我正在尝试按照 here. The class has multiple constructors with the same number of arguments, differing only by type, such as the class mentioned here 所述包装 C++ class。然而,Cython 无法决定调用哪个构造函数,给出错误 "no suitable method found"。

例如给定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 调用特定的构造函数。我只是不知道如何帮助它。谁能帮帮我?

您可以明确地提出您的论点:

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>,否则会给你一个不明确的重载错误。