将自定义代码添加到SWIG包装器

时间:2018-04-26 19:59:00

标签: python c++ 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时调用它。任何建议都表示赞赏。

1 个答案:

答案 0 :(得分:0)

我会回答我自己的问题。下面创建一个宏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;
};