4

次のPython(3.x)コードについて考えてみます。

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

同じ機能をCで書く方法は?

つまり、Cのメソッドを使用してオブジェクトを作成するにはどうすればよいですか?そして、それからインスタンスを作成しますか?

編集:ああ、ごめんなさい!私はPythonCAPIを介して同じ機能を意味しました。C APIを介してPythonメソッドを作成するにはどうすればよいですか?何かのようなもの:

PyObject *Foo = ?????;
PyMethod??? *bar = ????;
4

3 に答える 3

3

できません!Cには「クラス」がなく、structsだけがあります。また、structコード(メソッドまたは関数)を持つことはできません。

ただし、関数ポインタを使用して偽造することはできます。

/* 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();
于 2009-12-23T18:31:05.993 に答える
3

これが単純なクラスです(3.x用にhttp://nedbatchelder.com/text/whirlext.htmlから採用):

#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;
}
于 2009-12-23T19:14:43.743 に答える
2

ここにあるサンプルソースコードから始めることをお勧めします。これはPython3のソースの一部であり、たとえば、必要なこと(およびその他のいくつかのこと)を実行する方法を示すために特別に存在します。CAPIを使用します。モジュールを作成するには、そのモジュールで新しいタイプを作成し、そのタイプにメソッドと属性を付与します。これは基本的にソースの最初の部分であり、最終的には次の定義にXxo_Typeなります。次に、さまざまな種類の関数、気にしない他の種類の関数を定義する方法の例を取得し、最後に適切なモジュールオブジェクトとその初期化を行います(もちろん、そのほとんどをスキップしますが、モジュールオブジェクトと、対象のタイプの定義につながる初期化の部分はスキップします;-)。

そのソースを調査して特定のニーズに適合させる際に発生する可能性のある質問のほとんどは、ドキュメント、特に「オブジェクト実装サポート」のセクションで適切な回答がありますが、もちろん、ここでいつでも新しい質問を開くことができます(問題が最善です-多くの実際の質問を含む「質問」は常に面倒です!-)あなたがしていること、結果として期待していたこと、そして代わりにあなたが見ているものを正確に示す-そしてあなたは得るでしょういくつかの非常に有用なものを含む傾向がある答え;-)。

于 2009-12-23T19:15:11.217 に答える