我正在尝试使用SWIG将std :: map包装到python中,并且它工作得很好,除了它泄漏内存(我的代码如下)。
显然,SWIG自动释放返回的对象(Tuple
)内存,但不释放在其中分配的String
。我读过我可以使用%typemap(newfree)
进行显式释放,但不知道如何实现。
%typemap(out) std::pair<std::string, double> {
$result = PyTuple_Pack(2, PyUnicode_FromString($1.first.c_str()),
PyFloat_FromDouble($1.second));
};
%typemap(newfree) std::pair<std::string, double> {
// What to do here?
// delete[] $1.first.c_str() clearly not the way to go...
}
SWIG为pair
和string
预先定义了类型映射,因此您不需要自己编写它们:
test.i
%module test
// Add appropriate includes to wrapper
%{
#include <utility>
#include <string>
%}
// Use SWIG's pre-defined templates for pair and string
%include <std_pair.i>
%include <std_string.i>
// Instantiate code for your specific template.
%template(sdPair) std::pair<std::string,double>;
// Declare and wrap a function for demonstration.
%inline %{
std::pair<std::string,double> get()
{
return std::pair<std::string,double>("abcdefg",1.5);
}
%}
演示:
>>> import test
>>> p = test.sdPair('abc',3.5)
>>> p.first
'abc'
>>> p.second
3.5
>>> test.get()
('abcdefg', 1.5)