#假设模块名字是FMBus,并且被保存为fmbusmodule.c
#include"Python.h"
#include"structmember.h" //Python\Python36\include 路径下
#include"object.h" //Python\Python36\include 路径下
........
//定义对象
typedef struct {
PyObject_HEAD
int fd; /* open file descriptor: /dev/FMdev1? */
int addr; /* current address */
int value; /* address and value pairs*/
int pec; /* !0 => Packet Error Codes enabled */
} FMBus;
//定义各个回调函数,用于填充PyTypeObject
static PyObject *FMBus_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
FMBus *self;
// 1,alloc memory to self;
// 2,init member value of self-
self->fd = xx;
self->addr = 0x10000;
self->value = 0;
return (PyObject *)self;
}
static int FMBus_init(FMBus *self, PyObject *args, PyObject *kwds)
{
int bus = -1;
static char *kwlist[] = {"bus", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:__init__",
kwlist, &bus))
return -1;
if (bus >= 0) {
FMBus_open(self, args, kwds);
if (PyErr_Occurred())
return -1;
}
return 0;
}
//定义和填充 PyTypeObject 结构体
static PyTypeObject FMBus_type=
{
PyVarObject_HEAD_INIT(NULL, 0)
"FMBus", /* tp_name */
sizeof(FMBus), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)FMBus_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, /* tp_flags */
FMBus_type_doc, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
FMBus_methods, /* tp_methods */
0, /* tp_members */
FMBus_getset, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)FMBus_init, /* tp_init */
0, /* tp_alloc */
FMBus_new, /* tp_new */
};
//定义和填充 PyMethodDef 结构体
static PyMethodDef FMBus_methods[] = {
{"open", (PyCFunction)FMBus_open, METH_VARARGS | METH_KEYWORDS,
FMBus_open_doc},
{"close", (PyCFunction)FMBus_close, METH_NOARGS,
FMBus_close_doc},
{"read_byte", (PyCFunction)FMBus_read_byte, METH_VARARGS,
SMBus_read_byte_doc},
{"write_byte", (PyCFunction)FMBus_write_byte, METH_VARARGS,
SMBus_write_byte_doc}
。。。。。。
};
//定义和填充PyModuleDef
static struct PyModuleDef SMBusModule = {
PyModuleDef_HEAD_INIT,
"FMBus", /* m_name */
FMBus_module_doc, /* m_doc */
-1, /* m_size */
NULL, /* m_methods */
NULL, /* m_reload */
NULL, /* m_traverse */
NULL, /* m_clear */
NULL, /* m_free */
};
//最后,初始化模块
void PyInit_fmbus(void)
{
PyObject* m;
if (PyType_Ready(&FMBus_type) < 0)
return(NULL);
m = PyModule_Create(&FMBusModule);
if (m == NULL)
return (NULL);
Py_INCREF(&FMBus_type);
PyModule_AddObject(m, "FMBus", (PyObject *)&FMBus_type);
return (m);
}