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

2024-10-03 06:32:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有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 *)

也许使用typemap是一种可行的方法。我是新来的,所以不确定。。?你知道吗


Tags: 函数instringversionfunctionerrordslint
1条回答
网友
1楼 · 发布于 2024-10-03 06:32:06

%ReNAME只重命名目标语言的函数,即{{CD1>}将创建一个Python函数(GETVIEWONDOWN),它转发C/C++中定义的GETVIEWORN()。你知道吗

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

%rename("getVersion") _getVersion_Swig;

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

相关问题 更多 >