【python-C相互调用】python里的dict如何作为参数传入.so中的c语言函数

2025-02-27 04:27:41
推荐回答(1个)
回答1:

#include 
#include 
#include 

static PyObject *
wmf_reverse(PyObject *self, PyObject *args, PyObject *kwargs) { 
    static char* kwlist[] = {"name", NULL};
    char *name = NULL;
    PyObject *retval = NULL; 

    // 问题1: 只取一个字符串,format应该是"s"
    // >>> if(PyArg_ParseTupleAndKeywords(args,keyds,"isi",kwlist,&name))
    if (PyArg_ParseTupleAndKeywords(args, kwargs, "s", kwlist, &name)) {
        retval = (PyObject *)Py_BuildValue("i",1);
        printf("%s\n", name);
        // 问题2:不要释放
        // >>> free(name); 
    } else {
        retval = (PyObject *)Py_BuildValue("i",0);
    }
    return retval;


static PyMethodDef
wmf_methods[] = {
    {"reverse",(PyCFunction)wmf_reverse, METH_VARARGS | METH_KEYWORDS, "reverse"},
    // 问题3:方法定义表,应该用一条空记录来表示结束。
    {NULL, NULL, 0, NULL},
};

// 问题4:没有定义module
static struct PyModuleDef
wmf_module = {
    PyModuleDef_HEAD_INIT,
    "wmf",      /* name of module */
    NULL,       /* module documentation, may be NULL */
    -1,         /* size of per-interpreter state of the module,
                 or -1 if the module keeps state in global variables. */
    wmf_methods,
};

// 问题5:入口函数要声明为:PyMODINIT_FUNC
PyMODINIT_FUNC
PyInit_wmf(void) {
    // 问题6:Py_InitModule要初始化的是模块,不是方法。所以传方法定义是错误的。
    // 另外,python2.x是用Py_Init_module,python3.x改用PyModule_Create了。
    // 两者略有差别,自己注意一下吧。这里我用的是python3.x。
    //Py_InitModule("wmf",ExtestMethods);
    PyObject *m;
    m = PyModule_Create(&wmf_module);
    if (m == NULL) {
        return NULL;
    }
    return m;
}