gpt4 book ai didi

c++ - 从嵌套类的 SWIG 手册部分应用全局内部类解决方法时如何防止 SWIG 内存泄漏?

转载 作者:行者123 更新时间:2023-11-28 07:18:48 29 4
gpt4 key购买 nike

我正在应用 SWIG 手册中有关嵌套类的解决方法,该部分使用全局内部类。在这里,我将向您展示一个类似于手册中的版本,但为您尽可能地简化了。我还必须将内联定义 {} 添加到 method(),因为没有它 SWIG 根本无法工作。

// File outer.h
class Outer {
public:
class Inner {};
void method() {}
};


// File : example.i

// Redefine nested class in global scope in order for SWIG to generate
// a proxy class. Only SWIG parses this definition.
class Inner {};

%{
#include "outer.h"
%}
%include "outer.h"

%{
// SWIG thinks that Inner is a global class, so we need to trick the C++
// compiler into understanding this so called global type.
typedef Outer::Inner Inner;
%}

这很好用。但是,假设我更改 method() 以创建并返回嵌套的 Inner():

Inner method() { return Inner(); }

现在,结果如我所料(在实际更复杂的示例中),所以这不是我的问题。我的问题是,这会警告泄漏:重复应用

>>>Outer().method()

结果

swig/python detected a memory leak of type 'Outer::Inner *', no destructor found.

我知道如何解决此类问题 - 向 SWIG 提供违规类的完整定义。但是,已经提供了全局范围 Inner 类的完整定义。事实上,也提供了嵌套类的定义,但我猜 SWIG 忽略了它并且警告继续。

所以嵌套类按预期工作,除了我收到内存泄漏警告。

如何避免??

最佳答案

在 SWIG 文档 ( 6.27 Nested Classes ) 中,似乎有一个功能标志 %nestedworkaround 可以解决这个确切的问题:

%module x

class Inner {
};

%nestedworkaround Outer::Inner;

%inline %{
class Outer {
public:
class Inner {};
Inner method() { return Inner(); }
};
%}

%{
typedef Outer::Inner Inner;
%}

结果:

>>> import x
>>> x.Outer().method()
<x.Inner; proxy of <Swig Object of type 'Inner *' at 0x0000000002AE6880> >
>>> x.Outer().method()
<x.Inner; proxy of <Swig Object of type 'Inner *' at 0x0000000002AE69A0> >

没有那个标志,我在处理 SWIG 接口(interface)时收到警告:

x.i(15) : Warning 325: Nested class not currently supported (Inner ignored)

结果是这样的:

>>> import x
>>> x.Outer().method()
<Swig Object of type 'Outer::Inner *' at 0x0000000002AA6880>
>>> x.Outer().method()
swig/python detected a memory leak of type 'Outer::Inner *', no destructor found.
<Swig Object of type 'Outer::Inner *' at 0x0000000002AA69A0>

关于c++ - 从嵌套类的 SWIG 手册部分应用全局内部类解决方法时如何防止 SWIG 内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19828986/

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