python - 更改 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 的新手,所以不确定..?
解决方案
%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();
}
%}
推荐阅读
- ruby-on-rails - 在 Rails 中按下按钮后,如何使用排序的电影列表更新视图?
- java - WebFlux:上传文件的问题
- c - 最佳性能加法模 2^32 实现
- c# - 转换 IEnumerable
> 到 IObservable 带异常处理 - c++ - 在调试中构建 C++ 类的详细信息
- php - 照亮 - HasMany - 迭代
- fonts - macOS Mojave 上 Safari 12 中的字体系列/显示问题
- jquery - 使用 jquery 将每个添加的字段输入保存到 sessionStorage
- python - 使用 TweetTokenize 时出现不可散列类型的错误
- python - 如何解决make py2exe后程序创建文件的问题?