我正在尝试使用boost::shared_ptr's允许我在我的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')
%}
Run Code Online (Sandbox Code Playgroud)
这是警告:
In [2]: ptrtest.leak_memory()
swig/python detected a memory leak of type 'ofstream_ptr *', …Run Code Online (Sandbox Code Playgroud) 以下代码适用于Python 2:
from ctypes import *
## Setup python file -> c 'FILE *' conversion :
class FILE(Structure):
pass
FILE_P = POINTER(FILE)
PyFile_AsFile = pythonapi.PyFile_AsFile # problem here
PyFile_AsFile.argtypes = [py_object]
PyFile_AsFile.restype = FILE_P
fp = open(filename,'wb')
gd.gdImagePng(img, PyFile_AsFile(fp))
Run Code Online (Sandbox Code Playgroud)
但在Python 3中,pythonapi中没有PyFile_AsFile.
代码是testPixelOps.py之外的代码.