Reputation: 2664
I'm writing a python module in C that provides a class, wrapping a C API. The C API has some basic accessor methods that I'd like to present as a property in the python class. For example, say I have:
int libspam_get_eggs(spam_t *spam, int *eggs);
int libspam_set_eggs(spam_t *spam, int eggs);
I know how to create a class CSpam and add get_eggs() and set_eggs() methods to it, but I'd like to present eggs as a property instead. To solve this problem, I could put a python wrapper around the object that does:
class Spam(CSpam):
eggs = property(CSpam.get_eggs, CSpam.set_eggs)
But I'd like to do everything in the C API if possible. Is there a way to do this?
Upvotes: 6
Views: 1111
Reputation: 39853
You're looking for PyTypeObject.tp_getset
and the PyGetSetDef
struct.
The signature of the getter and setter functions should match
PyObject *libspam_get_eggs(PyObject *self, void *closure);
int libspam_set_eggs(PyObject *self, PyObject *value, void *closure);
where closure
is a void*
set on the PyGetSetDef
.
Upvotes: 7