Python 如何给 c 函数传递结构体参数

Python014

Python 如何给 c 函数传递结构体参数,第1张

 //test1.c# include <stdio.h># include <stdlib.h>struct Student

{    char name[30]    float fScore[3]

}void Display(struct Student su){    printf("-----Information------\n")    printf("Name:%s",su.name)    printf("Chinese:%.2f\n",su.fScore[0])    printf("Math:%.2f\n",su.fScore[1])    printf("English:%.2f",su.fScore[2])    printf("平均分数为:%.2f\n",(su.fScore[0]+su.fScore[1],su.fScore[2])/3)

}

#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

}