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

【python-C相互调用】关于python通过.so调用C函数来读取python里某个key的值并进行处理,一直无法将dict传到C中,求助
1. 首先是C中的包装函数定义

static PyObject *
Extest_reverse(PyObject *self, PyObject *args,PyObject *keyds)
{
//PyObject* keyds = PyDict_Keys(args);
static char* kwlist[] = {"name",NULL};
char *name; //将dict中的name里的值读到char* name中

PyObject* retval;

if(PyArg_ParseTupleAndKeywords(args,keyds,"isi",kwlist,&name))
{
retval = (PyObject *)Py_BuildValue("i",1);
printf("%s",name);
free(name);
return retval; //成功读取返回1
}
else
retval = (PyObject *)Py_BuildValue("i",0);
return retval; //未读取返回0
}
static PyMethodDef
ExtestMethods[] =
{
{"reverse",(PyCFunction)Extest_reverse,METH_VARARGS | METH_KEYWORDS,"reverse"},
};
void initwmf()
{
Py_InitModule("wmf",ExtestMethods);
}
2.python里的调用 .so已生成,将python 中定义的dict作为参数输入
import wmf
test = {'name':'wmf'}
result = wmf.reverse(test)
print(result)
返回结果一直是0,未读到对应key值的value,进一步查验返现,test这个dict就没有传进去,传入参数是NULL。求助定义的问题,还是调用的问题?如何解决

#include <stdio.h>
#include <stdlib.h>
#include <Python.h>

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;
}

追问

小白一个,您的代码还是执行不了啊:
错误1:
use of undeclared identifier 'PyModuleDef_HEAD_INIT'
错误2:
error: variable has incomplete type 'struct PyModuleDef'
wmf_module = {
note: forward declaration of 'struct PyModuleDef'
static struct PyModuleDef

温馨提示:答案为网友推荐,仅供参考

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网