首页 > 解决方案 > 将自定义代码添加到 SWIG 包装器

问题描述

我正在使用 SWIG 在 C++ 和 Python 之间进行接口。我想在生成的包装器中添加一些代码,以在结构中设置成员变量。我发现的最接近的是:

%allowexception TAxis::Min;
%exception TAxis::Min
%{
  $action
  do_something();
%}

struct TAxis
{
  double Min;
  double Max;
};

但是,当 TAxis::Min 被读取和写入时,这将调用 do_something()。我希望仅在写入 TAxis::Min 时调用它。任何建议表示赞赏。

标签: pythonc++swig

解决方案


我会回答我自己的问题。下面创建一个宏VAR_WITH_SET_CODE,可以用来在变量设置前后做一些事情。

%define VAR_WITH_SET_CODE(class, type, member, pre_code, post_code)
%extend class
{
  type member; 
}

%{
  #define class ## _ ## member ## _get(self) self->member
  #define class ## _ ## member ## _set(self, value) {pre_code} self->member = value; {post_code}  
%}
%enddef

VAR_WITH_SET_CODE(TAxis, double, Min, do_before();, do_after();)
VAR_WITH_SET_CODE(TAxis, double, Max, do_before();, do_after();)
struct TAxis
{
//double Min;
//double Max;
};

推荐阅读