return own type from Python extention?

Jeremy Moles jeremy at emperorlinux.com
Thu Sep 29 10:13:08 EDT 2005


Building a fully-fledged, custom Python object in C isn't a trivial
task; it isn't a hard one either, but it isn't trivial. :) Basically, as
far as I know, you'll need to create a PyTypeObject structure, populate
it accordingly, and then call a few setup functions on it...

// --------------------------------------------

static PyTypeObject WEE = {
...
};

Py_TypeReady(&WEE);

module = Py_InitModule*(...) // There are a few versions of this

PyModule_AddObject(module, "WEE", (PyObject*)(&WEE));

// ---------------------------------------------

This is all from memory--I know I left out having to at least INCREF the
static WEE. At any rate, I'm sure you can find some samples easy enough.
And if not, I can let you try and grok some of my extension code...

On Thu, 2005-09-29 at 15:59 +0200, elho wrote:
> Thx, but my Problem is to get my own type before.
> If I have a C-Type, I know how tu return it from the Python extention, 
> but how will it work with my own type?
> I expect something like the following:
> 
> static PyObject* wrap_MyFunction (PyObject* self, PyObject* args)
> {
>    :
>    MyPyType *myType = MyTypeNew ();
>    return (PyObject*)myType;
> }
> 
> How will the Konstructor-Funktion look for MyPyType to call this in C-Code.
> 
> ...If I explain my problem to confuesed here more informations:
> I have one function for MyPyType to construct it by calling from python:
> 
> static PyObject* PyMyType_new(PyTypeObject *type, PyObject *args, 
> PyObject *kwds)
> {
>      PyMyType *self;
>      self = (PyMyType*)type->tp_alloc(type, 0);
>      if (self != NULL) {
>          self->test = 0;
>      }
>      return (PyObject *)self;
> }
> 
> ..but how do I have to call this from C-Code or how will another 
> Funktion for this look like?
> 
> 
> 
> Jeremy Moles wrote:
> > You can use Py_BuildValue for most what you're probably going to need.
> > 
> > http://docs.python.org/api/arg-parsing.html
> > 
> > On Thu, 2005-09-29 at 15:39 +0200, elho wrote:
> > 
> >>I used the examples from the "Extending and Embedding the Python 
> >>Interpreter" tutorial and this works. I can use my types with python.
> >>But I do not know how to creat my own Python variable in an python 
> >>extending c-code. What will I have to creat this and return it to my 
> >>python programm?
> > 
> > 




More information about the Python-list mailing list