带swig的自动ptr

2024-10-04 01:32:07 发布

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

我试图包装一个使用AutoTypTR的C++库。我用的是威士忌 并希望生成python绑定。我看过swigdocu中关于如何使用swig和智能指针here的部分。但我不能让它工作。在

Swig生成的代码希望使用const初始化auto-ptr 引用,但auto ptr用非常数定义复制构造函数 参考,例如auto_ptr(auto_ptr&;)。生成的 代码不使用“discards const限定符”编译。当我手动 delete const编译fine限定符代码。在

我看到了很多邮件列表条目,但没有任何帮助。有人能吗 给我举个例子。我的非工作样本在这里:

%module auto_ptr_test
%{
#include <memory>
#include <iostream>
using namespace std;
%}
namespace std {
template <class T>
class auto_ptr {
    auto_ptr();
    auto_ptr(auto_ptr &);
    T *operator->() const;
};
}

%inline %{
class Test {
Test() {
    cout << "Test()" << endl;
}
public:
static std::auto_ptr<Test> create() const {
    return auto_ptr<Test>(new Test());
}
void greet() {
    cout << "hello" << endl;
}
};
%}

%template () std::auto_ptr<Test>;

我用cmake编译了它CMakeLists.txt文件公司名称:

^{pr2}$

Tags: 代码testautoincludetemplatenamespaceclassstd
2条回答

我在libRETS中找到了提示,您需要根据每个方法进行:

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

基本上,你想打开你从C++接收的AutoYPTR,然后在传递给C++之前把它包起来。要放入.i文件的代码示例如下:

    //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));

我不相信你能成功地用SWIG包装这段代码。问题是auto-u-ptr在复制时会更改所有权。这就是为什么它要求复制构造函数没有const。SWIG在内部管理对象所有权的方式意味着,如果没有大量自定义SWIG代码,您不太可能获得所需的所有权行为。在

相关问题 更多 >