首页 > 解决方案 > 更改 Python swigged C 函数的返回值类型

问题描述

我有一个 C++ 函数

Version getVersion(){ return Version("1.2.3.5");}

其中 Version 是一个类,包含“版本信息”,例如

class Version
{
    public:
                                                Version(const string& version = gEmptyString);
        bool                                    parse(const string& input);
        int                                     getMajor() const;
        int                                     getMinor() const;
        int                                     getPatch() const;
        int                                     getBuild() const;
        string                                  asString(const string& format = gEmptyString) const;


    private:
        int                                     mMajor;
        int                                     mMinor;
        int                                     mPatch;
        int                                     mBuild;
};

使用 Swig 包装此代码时,Python 用户在调用 getVersion() 函数时会返回一个 Version 对象。

从 Python 调用时,我想更改 getVersion() 函数的行为。而不是返回一个版本对象,我想返回一个字符串,代表版本值。

我尝试了以下方法:

%rename(getVersionHidden) getVersion;

%inline %{
std::string getVersion()
{
    Version v = getVersionHidden();
    return v.asString();
}
%}

但这不会编译:

   Error ... Call to undefined function 'getVersionHidden' in function 
   getVersion()
   Error E2285 P:\builds\dsl\wrappers\python\dslPYTHON_wrap.cxx 4434: Could not 
   find a match for 'Version::Version(const Version&)' in function getVersion()
   Error E2015 P:\builds\dsl\wrappers\python\dslPYTHON_wrap.cxx 16893: Ambiguity 
   between 'dsl::getVersion() at P:/libs/dsl/Common\dslCommon.h:8' and 
   'getVersion() at P:\builds\dsl\wrappers\python\dslPYTHON_wrap.cxx:4432' in 
   function _wrap_getVersionHidden(_object *,_object *)

也许使用类型映射是要走的路。我是 Swig 的新手,所以不确定..?

标签: pythonc++swig

解决方案


%rename 仅重命名目标语言的函数——也就是说,%rename("getVersionHidden") getVersion;将创建一个 Python 函数 (getVersionHidden),它转发 C/C++ 中定义的 getVersion()。

相反,您应该创建一个新函数,然后重命名它以覆盖否则会自动生成的 getVersion:

%rename("getVersion") _getVersion_Swig;

%inline %{
std::string _getVersion_Swig()
{
    Version v = getVersion();
    return v.asString();
}
%}

推荐阅读