0

How can I get Swig generate Python code as a class instead of free functions?

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

%include "SimulatorAppWrapper.hpp"

My wrapper source is fairly trivial:

class SimulatorAppWrapper
{
public:

    typedef std::map<const char*, const char*> ConfigSettings;

    SimulatorAppWrapper();

    ~SimulatorAppWrapper();

    void AddConfigKey(const char* k, const char* v); 

    int Run();
};

From here I generate Swig source and link against it using: swig -python -c++ SimulatorAppWrapper.i

However I check the build module I get the following where I have free functions instead of something like a class:

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

I would like to be able to do something like the following:

simApp = SimulatorAppWrapper
simApp.Run()

1 Answer 1

1

I can't see anything wrong with the SWIG .i or your .h.

But your test would be simApp = SimulatorAppWrapper() (note the parentheses) then either semicolon or new line before simApp.Run().

Also you should use from SimulatorAppWrapper import SimulatorAppWrapper since you have named your module SimulatorAppWrapper.

Finally, you do not need an underscore in dir(_SimulatorAppWrapper). The list you see is the set of SWIG wrapper functions which get called when you create instance, etc. For example when you call SimulatorAppWrapper() this actually calls new_SimulatorAppWrapper(). Try dir(SimulatorAppWrapper) (which in your original code will be dir() on the module object, but if you use the "from import" as I suggest above it will be dir() on your class).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.