SWIG 中的类型检查和重载方法

Type checking and overloaded methods in SWIG

我有一个 C++ 方法,可以调用为 x(const std::string &a, bool b=true)x(const SomeClass &object, bool b=true)

在 Python 中,我可以使用 x('Hello', True)x('Hello') 以及 x(someObject, True).

调用 SWIG 包装器

但是,如果我尝试 x('Hi', 'Hello') 之类的东西,swig 不会将 'Hello' 转换为布尔值,所以我得到 NotImplementedError: Wrong number or type of arguments for overloaded function.

如果第二个参数存在,我如何告诉它把第二个参数转换为 bool?

--- 更新 -------------------------------------- --------------

https://github.com/swig/swig/blob/master/CHANGES#L1527-L1581

上面的 link 似乎表明这是现在所需的行为,尽管它可以 'of course' 使用类型映射进行更改...?

您可以为 SWIG 编写类型映射,为任何输入调用 Python 对象协议函数 PyObject_IsTrue

%module test
%typemap(in) bool b "=PyObject_IsTrue($input);"
void foobar(bool b=true);

最后,我是这样修复的(可能会有后果...):

#if defined(SWIGPYTHON)
    %typemap(typecheck,precedence=SWIG_TYPECHECK_BOOL) bool {  = 1; }
    %typemap(in) bool { =PyObject_IsTrue($input); }
#endif

第一个类型映射告诉 swig,在 Python 中,一切都可以被视为 bool。 第二个来自@flexo 的回答,将匹配的参数转换为 C++ 布尔值。