Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have trouble parsing dictionary from python to C program using swing module. I have written a wrapper_dict.c and struct.c program.

wrapper.c 
    #include <Python.h>
    #include "struct.h"
    PyObject *dictionary(PyObject *self, PyObject *args) {
            PyObject *dict;
            int result;
            if (!PyArg_ParseTuple(args, "O", &dict))
                     return NULL;
            result = printBook(&dict);
            return Py_BuildValue("i", result);
    }
    static PyMethodDef dictMethods[] = {
             { "printBook", dictionary, 1 },
             { NULL, NULL }
    };
    void initdict() {
            PyObject *m;
            m = Py_InitModule("dict", dictMethods);
    }
Struct.c: 
    #include<stdio.h>
    #include<string.h>
    #include "struct.h"
    int printBook (struct Books *book) {
            printf(" Book title: %s\n", book->title);
            printf(" Book author: %s\n", book->author);
            printf(" Book subject: %s\n", book->subject);
            printf(" Book book_id: %d\n", book->book_id);
            return 1;
    }

Using dynamic loading:

   xyz@M:~/Python/Cprogam/work$ gcc -fpic -c $(pkg-config --cflags --libs python2) wrapper_dict.c struct.c
    xyz@M:~/Python/Cprogam/work$ gcc -shared wrapper_dict.o struct.o -o dictmod.so

When I passed the dictionary to printBook I see the printf statements returns bunch of garbage values.

 xyz@M:~/Python/Cprogam/work$ python
    Python 2.7.6 (default, Mar 22 2014, 22:59:38)
    [GCC 4.8.2] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import dict
    >>> books= { 'title':'C progamming', 'author' : 'J k', 'subject' : 'telecomm', 'book_id': '345524'}
    >>>
   >>> dict.printBook(books)
   Book title: t?"?/0l?
   Book author: s?D
   Book subject:
   Book book_id: 4
   1

Am I missing something? Kindly let me know. Thanks in advance.

share|improve this question
    
dict is a poor choice for the name of your module. It shadows the built-in type of the same name. –  Robᵩ 15 hours ago
    
Where is SWIG involved? Looks like a straight Python C extension to me... –  Mark Tolonen 11 hours ago
    
I don't think that would compile. You're passing a PyObject** to printBook, which takes a Books*. –  Mark Tolonen 11 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.