Embedding Python

Carsten Haese carsten.haese at gmail.com
Tue Jul 1 09:41:28 EDT 2008


Marcin Krol wrote:
> Hello everyone,
> 
> I'm trying to embed Python interpreter in C code, but in a specific way:
> loading compiled bytecode into a memory location and executing it (don't
> ask why, complicated reasons).
> 
> PyImport_ExecCodeModule seems like obvious candidate, docs say:
> 
> "Given a module name (possibly of the form package.module) and a code
> object read from a Python bytecode file or obtained from the built-in
> function compile(), load the module."
> [...]
>         mainobj = PyImport_ExecCodeModule("multiply", (PyObject *)
> python_code);
> [...]

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. 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.

Hope this helps,

--
Carsten Haese
http://informixdb.sourceforge.net



More information about the Python-list mailing list