tags:

views:

215

answers:

7

I have a python code computing a matrix, and I would like to use this matrix (or array, or list) from C code.
I wanted to pickle the matrix from the python code, and unpickle it from c code, but I could not find documentation or example on how to do this. I found something about marshalling data, but nothing about unpickling from C.

Edit : Commenters Peter H asked if I was working with numpy arrays. The answer is yes.

A: 

take a look at module struct ?

Francis
+5  A: 

You might want to use something more standardized, like JSON. You have a JSON module in Python 2.6. There are 6 different JSON modules for C.

You might want to use something more C-like, like the Python struct module. It can build a C-compatible object directly, saving you from pickling and unpickling. http://docs.python.org/library/struct.html

S.Lott
Struct seems better suited to write things like ioctl, or building structs in memory. Writing a binary blob does not make it easy to debug the c code. I guess I will go with the csv or json
shodanex
+1  A: 

Check out the chapter on Serializing Data in Mark Pilgrim's Dive Into Python. He states there that "The pickle protocol is Python-specific; there is no guarantee of cross-language compatibility. You probably couldn’t take the [...] pickle file you just created and do anything useful with it in Perl, PHP, Java, or any other language."

Perhaps JSON is a better alternative, also explained in that chapter.

Tim Pietzcker
+3  A: 

If it's just a matrix, you could just write it out as a CSV file. Look at the Python csv module for this. http://docs.python.org/library/csv.html

Chinmay Kanchi
+1  A: 

If you absolutely must use pickling, you can embed Python in your C program and unpickle in C via Python.

Corbin March
A: 

Besides JSON, there are also the Google Protocol Buffers which have 'native' support (from Google) for Python, C++ and Java -- and a number of third-party bindings to other languages including C.

Dirk Eddelbuettel
+1  A: 

Protocol Buffers are an interesting approach to serialize information in a cross-language way that's also quite compact and fast (support for C, as opposed to C++, isn't part of the protobuf package as released, but linking in some C++ code may be acceptable in some C projects, or there may be third-party implementations such as protobuf-c -- see here for a list of other third-party add-ons).

Alex Martelli