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.
dict
is a poor choice for the name of your module. It shadows the built-in type of the same name. – Robᵩ 15 hours agoPyObject**
toprintBook
, which takes aBooks*
. – Mark Tolonen 11 hours ago