Reputation: 55
While in the process of learning the C API for CPython I wanted to modify the xxsubtype.c template example that contains spamlist and spamdict to create spamtuple. The does not work directly, I believe, since tuples are immutable and so you cannot use tp_init. I believe that you have to use tp_new. The goal is to have the following python code work:
import xxsubtype
s = xxsubstype.spamtuple((1,2,3))
What I have done so far is change spamlist
to spamtuple
; change Py_List_Type
to Py_Tuple_Type
etc and then add a spamtuple_new
:
static PyObject *
spamtuple_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
spamtupleobject *self;
self = (spamtupleobject *)PyTuple_Type.tp_new(type, args, kwds);
if (self != NULL) {
self->state = 0; // Initialize custom attributes
}
return (PyObject *)self;
}
Then update spamtuple_type with
static PyTypeObject spamtuple_type = {
PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
"xxsubtype.spamtuple",
sizeof(spamtupleobject),
0,
0, /* tp_dealloc */
...
(initproc)spamtuple_init, /* tp_init */
0, /* tp_alloc */
spamtuple_new, /* tp_new */
};
When I load the module up in python and attempt
s = xxsubstype.spamtuple((1,2,3))
I get a seg fault. Looking for help in general how to accept tuples as arguments. Eventually I would like to be able to do:
s = xxsubtype.spamtuple((1,2,3), data=data)
where data is a tuple or reference to a class. Any help would be appreciated.
Upvotes: 0
Views: 53