6

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?

1 Answer 1

7

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.