[Python/C] Help me.. How to passa dictionary to C function?

±è»ó¿Ï sangwan at kisti.re.kr
Wed Mar 31 03:30:17 EST 2004


I'm a newbie in Python and Python/C API..

I have a simple question. I want to access python dictionary data type from
C extension module.

---- spam.c ----
#include <Python.h>

PyObject *wrap_clear(PyObject *self, PyObject *args) {
  int count;
  PyObject *dict;
  PyObject *newdict;

  newdict = PyDict_New(); // newdict is created in C module

  if (!PyArg_Parse(args, "O", &PyDict_Type, &dict)) {
      return NULL;
  }

  if (PyDict_Check(newdict)) {  // newdict is a dictionary
     printf("newdict is ok\n");
  } else {
     printf("newdict is not ok\n");
  }

  if (PyDict_Check(dict)) { // dict is from python
     printf("dict is ok\n");
  } else {
     printf("dict is not ok\n");
  }

  return Py_BuildValue("i", 0);
}


static PyMethodDef spamMethods[] = {
  {"clear", wrap_clear, 1 },
  { NULL, NULL }
};

void initspam() {
  PyObject *m;

  m = Py_InitModule("spam", spamMethods);
}
------------


$
gcc -fpic -c -I/usr/local/python/include/python2.3 -I/usr/local/python/lib/p
ython2.3/config spam.c
$ gcc -shared spam.o -o spam.so
$ python
Python 2.3.3 (#1, Mar 29 2004, 18:57:19)
[GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-113)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import spam
>>> d = {"count":1}
>>> d
{'count': 1}
>>> spam.clear(d)
newdict is ok  -------> newdict is a dictionary
dict is not ok  --------> but dict is not a dictionary
0
>>>

How can i access to the dictionary from C module??

Thanks in advance..






More information about the Python-list mailing list