Python C extension - getting dict argument as argument

I am writing a C extension and I completely lost how to get the dict as an argument. Since the documents do not have any specifics on how to do this, I tried to parse the argument as a Python object and then manipulate it as a dict:

PyTypeObject *dict; if(!PyArg_ParseTuple(args, "o", &dict)) return NULL; 

But the code does not execute on parsing:

 Python 2.7.2 (default, Jun 20 2012, 16:23:33) [GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import plotting >>> plotting.plot({'wff':0}) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: must be impossible<bad format char>, not dict 

As far as I understand from the error message, the char format is incorrect (I thought that "o" should represent any Python object).

What is the best way to parse a Python dict into a C pointer? I am digging documentation, but I have not found anything like it.

Thanks.

+4
source share
1 answer

You have a couple of problems here. First of all, the PyTypeObject type PyTypeObject designed specifically for the structure that defines the type. You can learn more about type objects here: http://docs.python.org/2/c-api/typeobj.html This is not what you want. For a pointer to an arbitrary Python object, you want to use PyObject* .

Secondly, the type code for any Python object is "O" (upper case), not "O" . If you want to do a type check that it is a dictionary, you can also use "O!" To do this, you need to pass the address of the object of the type, followed by the address of PyObject* , which you want to save the returned PyObject* to, For example:

 PyObject* dict; PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict); 

This will return the object to a * dict pointer and raise a TypeError if it is not a dict. However, if you absolutely do not need this, I would recommend against this in favor of checking whether the object implements the display interface. But that is another question.

+9
source

Source: https://habr.com/ru/post/1444641/


All Articles