更改Python Swiged C函数的返回值类型

时间:2018-06-29 18:28:59

标签: python c++ swig

我有一个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()函数的行为。我不希望返回Version对象,而是要返回一个字符串,表示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的新手,所以不确定。

1 个答案:

答案 0 :(得分:1)

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