sib*_*net 5 python constructor overriding cython python-2.7
我在通过 Cython 访问 C++ 类中的重载构造函数时遇到问题。我正在尝试按照此处所述包装 C++ 类。该类有多个参数数量相同的构造函数,仅类型不同,例如这里提到的类。但是,Cython 无法决定调用哪个构造函数,从而给出错误“找不到合适的方法”。
例如,给定 foo.h 如下
class Foo
{
public:
int which_constructor;
Foo(int){ which_constructor = 1; }
Foo(bool){ which_constructor = 2; };
~Foo();
};
Run Code Online (Sandbox Code Playgroud)
和 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
Run Code Online (Sandbox Code Playgroud)
和一个安装文件 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++",
)
)
)
Run Code Online (Sandbox Code Playgroud)
当我尝试编译时,出现以下错误
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
Run Code Online (Sandbox Code Playgroud)
如果我删除 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
Run Code Online (Sandbox Code Playgroud)
一定要强制转换为 to<bool_t>和 not <bool>,否则会给你一个不明确的重载错误。