Convert Python dictionary into C like structure

烈酒焚心 提交于 2019-12-12 02:57:00

问题


I am a newbie in Python and C and I would like to know how to put dictionary elements into a C like structure (struct).

For example, here is my structure:

typedef struct
{
    int dim;
    float *Tab1;
    float *Tab2;
}  
Tableaux;

Here is my dictionary in Python:

Tableaux = {}
Tableaux["dim"]=None
Tableaux["Tab1"]=[]
Tableaux["Tab2"]=[]

Here is my interface function:

static PyObject* py_initTab(PyObject* self, PyObject* args)
{
    PyObject* dict;
    Tableaux Tab;
    if (!PyArg_ParseTuple(args, "O!", &dict))  
        return NULL;        

     Tab.Tab1=dict["Tab1"]; // How could I do something like that?      

     return Py_BuildValue("");
}

回答1:


You can use PyDict_GetItem() for that:

PyObject* pytab1 = PyDict_GetItemString(dict, "Tab1");

Since the result is a list, you can use these calls to examine it

This documentation explains how to convert primitive types between C and Python.



来源:https://stackoverflow.com/questions/30217561/convert-python-dictionary-into-c-like-structure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!