How do I create a vanilla object in C?

R

rnichols

I need to create a vanilla object in C, something I can do
PyObject_SetAttr on. Obviously, I do something somewhat like this every
time I create a minimal python class. I need to know how to do this in C
though.
 
C

Carl Banks

I need to create a vanilla object in C, something I can do
PyObject_SetAttr on.  Obviously, I do something somewhat like this every
time I create a minimal python class.  I need to know how to do this in C
though.


First of all, if you don't need to share this object with any Python
code, then I'd suggest you just use a dict (create with PyDict_New).

If you do need to share it with Python, one thing to consider is
whether it isn't easier to create the object in Python and pass it to
the C code.

If these suggestions aren't suitable, then you'll have to create a new
vanilla type, then create an instance of that type. Unfortunately
it's not too convenient from C. It's easy enough to define types and
C (see the C-API documentation), but in order to use PyObject_SetAttr
on it you'll have to make sure the type has a dictionary, so you'd
have to set the tp_dictoffset member to the offset of your dict in the
Python structure.

Another thing you can do is to call type directly (as you can do in
Python) with the name, bases, dict, as in the following example (error
checking and reference counting omitted):

name = PyString_FromString("vanilla");
bases = PyTuple_New(0);
dict = PyDict_New();
vanilla_type = PyObject_CallObject(
&PyType_Type,name,bases,dict,0);

Then call the vanilla type (however you create it) to get a vanilla
object:

vanilla_object = PyObject_CallObject(vanilla_type,0);


Definitely not the most straightforward thing to do from C.


Carl Banks
 
S

sturlamolden

name = PyString_FromString("vanilla");
bases = PyTuple_New(0);
dict = PyDict_New();
vanilla_type = PyObject_CallObject(
        &PyType_Type,name,bases,dict,0);

Then call the vanilla type (however you create it) to get a vanilla
object:

vanilla_object = PyObject_CallObject(vanilla_type,0);

Definitely not the most straightforward thing to do from C.


It is much easier to do this from Cython.

cdef class foo:
# fields stored in C struct
pass

class foo:
# fields stored in Python dict
pass

The let the Cython compiler generate the C code you need.

http://docs.cython.org/src/tutorial/cdef_classes.html
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,044
Latest member
RonaldNen

Latest Threads

Top