C语言中的Python实例方法
考虑以下的Python(3.x)代码:
class Foo(object):
def bar(self):
pass
foo = Foo()
我该如何用C语言写出相同的功能呢?
我的意思是,如何在C语言中创建一个对象并给它一个方法?然后再从这个对象创建一个实例?
编辑:哦,抱歉!我指的是通过Python的C API实现相同的功能。如何通过它的C API创建一个Python方法呢?类似于:
PyObject *Foo = ?????;
PyMethod??? *bar = ????;
3 个回答
2
我建议你从这个示例源代码开始学习,这里的代码是Python 3的一部分,专门用来给你展示如何实现你需要的功能(还有其他一些功能)。它主要是教你如何使用C语言的API来创建一个模块,在这个模块里定义一个新类型,并为这个类型添加方法和属性。这个过程的第一部分就是定义Xxo_Type
,接下来你会看到如何定义各种类型的函数,还有一些你可能不太关心的其他类型,最后是模块对象本身及其初始化过程(当然你可以跳过大部分内容,但模块对象和它的初始化部分是必须了解的,这些部分会引导你到你感兴趣的类型定义)。
在你学习和调整这个源代码以满足你的具体需求时,可能会有很多问题,而这些问题在文档中都有很好的答案,特别是在“对象实现支持”部分。当然,你也可以在这里提出新问题(每个问题最好只问一个,这样更清晰,避免一个“问题”里有很多实际的问题,那样会让人困扰!),具体说明你在做什么、你期待的结果是什么,以及你实际看到的结果是什么。这样你会得到一些非常有用的回答;-)。
3
你不能这样做!C语言没有“类”,它只有struct
(结构体)。而且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();
3
这里有一个简单的类(改编自 http://nedbatchelder.com/text/whirlext.html,适用于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;
}