繁体   English   中英

如何使用shared_ptr和SWIG避免内存泄漏

[英]How to avoid memory leak with shared_ptr and SWIG

我正在尝试使用boost::shared_ptr来允许我在我的python脚本中使用c ++文件I / O流对象。 但是,生成的包装器警告我它正在泄漏内存。

这是一个显示问题的最小.i文件:

%module ptrtest

%include "boost_shared_ptr.i"
%include "std_string.i"

%shared_ptr( std::ofstream )

%{
#include <fstream>
#include <boost/shared_ptr.hpp>

typedef boost::shared_ptr< std::ofstream > ofstream_ptr;

ofstream_ptr mk_out(const std::string& fname ){
    return ofstream_ptr( new std::ofstream( fname.c_str() ) );
}

%}

ofstream_ptr mk_out(const std::string& fname );


%pythoncode %{

def leak_memory():
    ''' demonstration function -- when I call
        this, I get a warning about memory leaks
    ''''
    ostr=mk_out('/tmp/dont_do_this.txt')


%}

这是警告:

In [2]: ptrtest.leak_memory()
swig/python detected a memory leak of type 'ofstream_ptr *', no destructor found.

有没有办法修改.i文件告诉接口如何正确处理shared_ptr?

您的示例缺少两部分来运行析构函数:

  1. 由于SWIG对std::ofstream一无所知,因此默认行为除了传递一个不透明的句柄之外什么都不做。 请参阅我的另一个答案,以进一步讨论此问题。

    这里的修复是为你的接口文件中的std::ofstream提供一个空的定义,以说服SWIG它知道足够多做更多,即使你不打算暴露任何成员。

  2. SWIG需要查看typedef本身 - 在%{ %}内部它直接传递给输出模块,而不是在包装本身中使用。

因此,您的示例变为:

%module ptrtest

%include "boost_shared_ptr.i"
%include "std_string.i"

%shared_ptr( std::ofstream )

namespace std {
  class ofstream {
  };
}

%{
#include <fstream>
#include <boost/shared_ptr.hpp>

typedef boost::shared_ptr< std::ofstream > ofstream_ptr;

ofstream_ptr mk_out(const std::string& fname ){
    return ofstream_ptr( new std::ofstream( fname.c_str() ) );
}
%}

typedef boost::shared_ptr< std::ofstream > ofstream_ptr;
ofstream_ptr mk_out(const std::string& fname );

%pythoncode %{
def leak_memory():
    ostr=mk_out('/tmp/dont_do_this.txt')
%}

为了将来参考,您可以避免重复只存在于带有%inline的.i文件中的内容:

%inline %{
typedef boost::shared_ptr< std::ofstream > ofstream_ptr;

ofstream_ptr mk_out(const std::string& fname ){
    return ofstream_ptr( new std::ofstream( fname.c_str() ) );
}
%}

其中一次声明,定义和包装它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM