如何让Swig生成Python类而不是自由函数

How to get Swig to generate a Python class instead of free functions?

本文关键字:自由 函数 Python Swig 生成      更新时间:2023-10-16

如何让Swig将Python代码生成为类而不是自由函数?

%module SimulatorAppWrapper
%{
#define SWIG_FILE_WITH_INIT
#include "SimulatorAppWrapper.hpp"
%}
%include "SimulatorAppWrapper.hpp"

我的包装器来源相当琐碎:

class SimulatorAppWrapper
{
public:
    typedef std::map<const char*, const char*> ConfigSettings;
    SimulatorAppWrapper();
    ~SimulatorAppWrapper();
    void AddConfigKey(const char* k, const char* v); 
    int Run();
};

从这里我生成Swig源并使用以下链接:swig-python-c++模拟器AppWrapper.i

然而,我检查了构建模块,我得到了以下内容,其中我有免费的函数,而不是类:

>>> import SimulatorAppWrapper
>>> dir(_SimulatorAppWrapper)
['SWIG_PyInstanceMethod_New', 'SimulatorAppWrapper_AddConfigKey', 'SimulatorAppWrapper_Run', 'SimulatorAppWrapper_swigregister', '__doc__', '__file__', '__name__', '__package__', 'delete_SimulatorAppWrapper', 'new_SimulatorAppWrapper']

我希望能够做以下事情:

simApp = SimulatorAppWrapper
simApp.Run()

我看不出SWIG.I或你的.h 有什么问题

但您的测试将是simApp = SimulatorAppWrapper()(注意括号),然后是分号或simApp.Run()之前的新行。

此外,您应该使用from SimulatorAppWrapper import SimulatorAppWrapper,因为您已将模块命名为SimulatorAppWrapper

最后,dir(_SimulatorAppWrapper)中不需要下划线。您看到的列表是创建实例等时调用的SWIG包装函数集。例如,当您调用SimulatorAppWrapper()时,它实际上调用new_SimulatorAppWrapper()。尝试dir(SimulatorAppWrapper)(在您的原始代码中,它在模块对象上是dir(),但如果您使用我上面建议的"from import",它在您的类上将是dir())。