在上一篇中我们已经使用c语言实现了一个最简单的扩展模块,这一篇中将在其基础上进行功能的丰富。
首先来考虑如何从外部的Python向C模块传递进参数,foo_bar2展示了如何向C模块传递整数,浮点数,字符串三个参数,其中"ids"指明了传入参数的数据类型。PyArg_ParseTuple负责对args进行解析,若解析失败则返回0.
#include <Python.h>

static PyObject* foo_bar(PyObject* self, PyObject* args) {
    Py_RETURN_NONE;
}

static PyObject* foo_bar2(PyObject* self, PyObject* args) {
    
int iNum;
    
double fNum;
    
char* str;
    
if (!PyArg_ParseTuple(args, "ids"&iNum, &fNum, &str)) {
        
return NULL;
    }
    Py_RETURN_NONE;
}
static PyMethodDef foo_methods[] = {
    {
"bar",(PyCFunction)foo_bar,METH_NOARGS,NULL},
    {
"bar2", (PyCFunction)foo_bar2,METH_VARARGS,NULL},
    {NULL,NULL,
0,NULL}
};

PyMODINIT_FUNC initfoo() {
    Py_InitModule3(
"foo", foo_methods, "My first extension module.");
}

相关文章: