更改 return swigged C 函数的 Python 值类型

Change return value type of Python swigged C function

我有一个 C++ 函数

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

其中版本是 class,持有 "Version information",例如

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() 函数的行为。我不想 return 一个 Version 对象,而是 return 一个字符串,表示 Version 值。

我尝试了以下方法:

%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 的新手,所以不确定..?

%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();
}
%}