[Pyrex] How to deal with a block of memory when pickling?

Robert Bradshaw robertwb at math.washington.edu
Thu Mar 20 14:49:04 CET 2008


On Mar 20, 2008, at 6:42 AM, Simon King wrote:

> Good afternoon!
>
> I guess that the following has a standard solution, but i don't  
> know it.
>
> Using cython (hope that the pyrex list also answers cython questions),

cython-dev at codespeak.net is the official Cython mailing list, but  
many of us lurk here too (as there are often common questions).

> I cdefined some class MTX (it is a wrapper for C-MeatAxe matrices).  
> One of
> the attributes is a pointer p to a block of memory that defines the
> coefficients of the matrix.
>
> Now i want to pickle it. One obvious way is to get a list of matrix
> entries and work with it. But this is too slow. Is there a more  
> direct way
> to handle the block of memory p is pointing at?
>
> I tried to make a type cast of p to char* and to read this as a  
> string.
> In some cases it worked, and going the way back (string -> char*)
> reconstructed the memory block p was pointing at.
>  However, sometimes apparently it was not clear to python how long the
> string is supposed to be; so i got an empty string, and the  
> reconstruction
> failed.
>
> What can i do?

Use the PyString_FromStringAndSize function. (Otherwise it assumes a  
null character is the end of the string, per C convention.)

- Robert




More information about the Pyrex mailing list