Domanda

Si consideri il seguente codice Python (3.x):

class Foo(object):
    def bar(self):
        pass
foo = Foo()

Come scrivere la stessa funzionalità in C?

Voglio dire, come si crea un oggetto con un metodo in C? E poi creare un'istanza da essa?

Modifica : Oh scusa! Intendevo la stessa funzionalità tramite Python C API. Come creare un metodo di Python tramite la sua API C? Qualcosa di simile:

PyObject *Foo = ?????;
PyMethod??? *bar = ????;
È stato utile?

Soluzione

Ecco una semplice classe (adattato da http://nedbatchelder.com/text/whirlext.html per 3.x):

#include "Python.h"
#include "structmember.h"

// The CountDict type.

typedef struct {
   PyObject_HEAD
   PyObject * dict;
   int count;
} CountDict;

static int
CountDict_init(CountDict *self, PyObject *args, PyObject *kwds)
{
   self->dict = PyDict_New();
   self->count = 0;
   return 0;
}

static void
CountDict_dealloc(CountDict *self)
{
   Py_XDECREF(self->dict);
   self->ob_type->tp_free((PyObject*)self);
}

static PyObject *
CountDict_set(CountDict *self, PyObject *args)
{
   const char *key;
   PyObject *value;

   if (!PyArg_ParseTuple(args, "sO:set", &key, &value)) {
      return NULL;
   }

   if (PyDict_SetItemString(self->dict, key, value) < 0) {
      return NULL;
   }

   self->count++;

   return Py_BuildValue("i", self->count);
}

static PyMemberDef
CountDict_members[] = {
   { "dict",   T_OBJECT, offsetof(CountDict, dict), 0,
               "The dictionary of values collected so far." },

   { "count",  T_INT,    offsetof(CountDict, count), 0,
               "The number of times set() has been called." },

   { NULL }
};

static PyMethodDef
CountDict_methods[] = {
   { "set",    (PyCFunction) CountDict_set, METH_VARARGS,
               "Set a key and increment the count." },
   // typically there would be more here...

   { NULL }
};

static PyTypeObject
CountDictType = {
   PyObject_HEAD_INIT(NULL)
   0,                         /* ob_size */
   "CountDict",               /* tp_name */
   sizeof(CountDict),         /* tp_basicsize */
   0,                         /* tp_itemsize */
   (destructor)CountDict_dealloc, /* tp_dealloc */
   0,                         /* tp_print */
   0,                         /* tp_getattr */
   0,                         /* tp_setattr */
   0,                         /* tp_compare */
   0,                         /* tp_repr */
   0,                         /* tp_as_number */
   0,                         /* tp_as_sequence */
   0,                         /* tp_as_mapping */
   0,                         /* tp_hash */
   0,                         /* tp_call */
   0,                         /* tp_str */
   0,                         /* tp_getattro */
   0,                         /* tp_setattro */
   0,                         /* tp_as_buffer */
   Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags*/
   "CountDict object",        /* tp_doc */
   0,                         /* tp_traverse */
   0,                         /* tp_clear */
   0,                         /* tp_richcompare */
   0,                         /* tp_weaklistoffset */
   0,                         /* tp_iter */
   0,                         /* tp_iternext */
   CountDict_methods,         /* tp_methods */
   CountDict_members,         /* tp_members */
   0,                         /* tp_getset */
   0,                         /* tp_base */
   0,                         /* tp_dict */
   0,                         /* tp_descr_get */
   0,                         /* tp_descr_set */
   0,                         /* tp_dictoffset */
   (initproc)CountDict_init,  /* tp_init */
   0,                         /* tp_alloc */
   0,                         /* tp_new */
};

// Module definition

static PyModuleDef
moduledef = {
    PyModuleDef_HEAD_INIT,
    "countdict",
    MODULE_DOC,
    -1,
    NULL,       /* methods */
    NULL,
    NULL,       /* traverse */
    NULL,       /* clear */
    NULL
};


PyObject *
PyInit_countdict(void)
{
    PyObject * mod = PyModule_Create(&moduledef);
    if (mod == NULL) {
        return NULL;
    }

    CountDictType.tp_new = PyType_GenericNew;
    if (PyType_Ready(&CountDictType) < 0) {
        Py_DECREF(mod);
        return NULL;
    }

    Py_INCREF(&CountDictType);
    PyModule_AddObject(mod, "CountDict", (PyObject *)&CountDictType);

    return mod;
}

Altri suggerimenti

Non è possibile! C non ha "classi", ha solo structs. E un struct non può avere codice (metodi o funzioni).

È possibile, tuttavia, fingere con puntatori a funzione:

/* struct object has 1 member, namely a pointer to a function */
struct object {
    int (*class)(void);
};

/* create a variable of type `struct object` and call it `new` */
struct object new;
/* make its `class` member point to the `rand()` function */
new.class = rand;

/* now call the "object method" */
new.class();

Vi suggerisco di iniziare a partire dal codice sorgente di esempio qui - è parte di fonti Python 3 di, ed esiste specificamente visualizzare, per esempio, come eseguire ciò che si richiede (e poche altre cose oltre) - utilizzare l'API C per creare un modulo, fare un nuovo tipo in tale modulo, dotare tale tipo con metodi e attributi. Questo è fondamentalmente la prima parte della sorgente, che si conclude con la definizione di Xxo_Type - quindi si ottiene esempi di come definire i vari tipi di funzioni, alcuni altri tipi è possibile che non si preoccupano, e, infine, l'oggetto modulo appropriato e la sua inizializzazione (si può saltare la maggior parte che naturalmente, anche se non il modulo oggetto e le parti della sua inizializzazione che portano alla definizione del tipo di interesse; -.)

La maggior parte delle domande che potreste avere durante gli studi e l'adattamento quella fonte per le vostre esigenze specifiche hanno buone risposte in la documentazione , soprattutto nella href="http://docs.python.org/3.1/c-api/objimpl.html" rel="nofollow sezione su "oggetto di supporto all'attuazione" - ma naturalmente si può sempre aprire una nuova domanda qui (uno per ogni problema sarebbe meglio - una "domanda" con molti effettivi domande è sempre un fastidio ! -) che mostra esattamente quello che stai facendo, quello che ti aspettavi di conseguenza, e ciò che state vedendo, invece - e avrete le risposte che tendono ad includere alcuni tra quelli abbastanza utili; -).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top