auto_ptr with swig

╄→尐↘猪︶ㄣ 提交于 2019-12-02 00:57:39

I do not believe you are going to be able to successfully wrap this code in SWIG. The problem is that auto_ptr changes ownership when it copies. This is why it requires the copy constructor to not have const. The way that SWIG manages ownership of objects internally means that the it is unlikely you'll get the desired ownership behavior without a lot of custom SWIG code.

I found hint how to do it in libRETS, and you need to do it on per-method basis:

http://code.crt.realtors.org/projects/librets/browser/librets/trunk/project/swig/auto_ptr_release.i?rev=HEAD

Basically you want to unwrap auto_ptr you receive from C++ and wrap it before passing to C++. Example of code to be put into .i file is:

    //original prototype:
    //virtual void SetSomething(std::auto_ptr<ValueClass> value) = 0;
    //replacement to be generated by SWIG:
    %extend{
        void SetSomething(ValueClass *value){
            std::auto_ptr<ValueClass> tmp(value);
            $self->SetSomething(tmp);
        }
    }


  //retrieving object wrapped in auto_ptr using swig macro:
  %define SWIG_RELEASE_AUTO_PTR(RETURN_TYPE, METHOD_NAME, PROTO, ARGS)
    %extend {
    RETURN_TYPE * METHOD_NAME PROTO {
        std::auto_ptr<RETURN_TYPE> auto_result = self->METHOD_NAME ARGS;
        return auto_result.release();
    }
  }
  %enddef
  // and then inside class:
  // virtual auto_ptr<ValueClass> SomeMethod(const string& foo) = 0;
  // replaced with:
  SWIG_RELEASE_AUTO_PTR(ValueClass,SomeMethod,(const string& foo),(foo));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!