gpt4 book ai didi

c++ - SWIG - 包装 std::pair 字符串时内存泄漏

转载 作者:行者123 更新时间:2023-11-30 03:18:28 27 4
gpt4 key购买 nike

我正在尝试使用 SWIG 将 std::map 包装到 python,它工作得很好,除了它会泄漏内存(我下面的代码)。

显然,SWIG 会自动释放返回对象(元组)的内存,但不会释放其中分配的 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 为 pairstring 预定义了类型映射,因此您无需自己编写它们:

测试.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)

关于c++ - SWIG - 包装 std::pair 字符串时内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54733078/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com