I am attempting to create python bindings for some C++ code using swig. I seem have run into a problem trying to create python properties from some accessor functions I have for methods like the following:
class Player {
public:
void entity(Entity* entity);
Entity* entity() const;
};
I tried creating a property using the python property function but it seems that the wrapper classes swig generates are not compatible with it at least for setters.
How do you create properties using swig?
Ooh, this is tricky (and fun). SWIG doesn’t recognize this as an opportunity to generate @property: I imagine it’d be all too easy to slip up and recognize lots of false positives if it weren’t done really carefully. However, since SWIG won’t do it in generating C++, it’s still entirely possible to do this in Python using a small metaclass.
So, below, let’s say we have a Math class that lets us set and get an integer variable named “pi”. Then we can use this code:
example.h
example.i
example.cpp
util.py
somefile.py
So the end result is just that you have to create a wrapper class for every SWIG Python class and then type two lines: one to mark which methods should be converted in properties and one to bring in the metaclass.