How to unpickle from C code
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 marshall开发者_开发技巧ing data, but nothing about unpickling from C.Edit : Commenters Peter H asked if I was working with numpy arrays. The answer is yes.
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
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
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).
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.
If you absolutely must use pickling, you can embed Python in your C program and unpickle in C via Python.
- A quick example from Linux Journal
- Python Docs
- How do you call Python code from C code?
take a look at module struct
?
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.
精彩评论