Embedding Python

Marcin Krol mrkafk at gmail.com
Tue Jul 1 12:07:49 EDT 2008


Carsten Haese wrote:

> python_code is a C string containing the raw bytes from your pyc file. 
> Casting that to a PyObject pointer will not magically transform it into 
> a Python code object. 

<scratching my head> well yeah, I kind of didn't think that through..


A pyc file contains the following:
> 
> 1) An 8 byte header containing a magic number.
> 2) A "marshal" serialization of the code object.
> 
> So, in order to transform those contents into a code object, you need to 
> skip the 8 byte header and an unmarshal the rest. Basically, replace the 
> line above with something like this:
> 
>         codeobj = PyMarshal_ReadObjectFromString(python_code+8, size-8);
>         mainobj = PyImport_ExecCodeModule("multiply", codeobj);
> 
> where codeobj is of type (PyObject *).
> 
> Once that works, add magic number checking and exception handling to taste.


Thanks. That's exactly what I was looking for.




More information about the Python-list mailing list