我在通过 Cython 访问 C++ 类中的重载构造函数时遇到问题。我正在尝试包装一个 C++ 类,如 here 所述.该类有多个参数数量相同的构造函数,仅类型不同,例如提到的类 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 调用特定的构造函数。我只是不知道如何帮助它。谁能帮帮我?
请您参考如下方法:
你可以显式地表达你的论点:
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> ,否则会给你一个不明确的重载错误。
