Embedding Python

Marcin Krol mrkafk at gmail.com
Tue Jul 1 18:11:02 CEST 2008

Hello everyone,

In the meantime I managed to work out another solution, mainly thanks to 
reading the source code of some OSS projects. I post it here so somebody
else looking for solution to this problem had the example available:

#include <Python.h>
#include <stdio.h>
#include <stdlib.h>
#include <syslog.h>
#include <unistd.h>

static FILE *read_module(const char *cpathname, long mtime)
   FILE *fp;
   long magic;
   long pyc_mtime;

   fp = fopen (cpathname, "rb");
   if (fp == NULL)
     return NULL;

   magic = PyMarshal_ReadLongFromFile (fp);
   if (magic != PyImport_GetMagicNumber())
       return NULL;

   pyc_mtime = PyMarshal_ReadLongFromFile (fp);
   if (mtime && pyc_mtime != mtime)
       return NULL;

   return fp;

int main(int argc, char **argv)
         int size;

         PyCodeObject *mainobj, *pycode;
         PyObject *result, *mainmodule, *maindict;
         mainmodule = PyImport_AddModule("__main__");
         maindict = PyModule_GetDict(mainmodule);

         FILE *f = read_module("multiply.pyc", 0L);
         pycode = (PyCodeObject *) PyMarshal_ReadObjectFromFile(f);
         printf("pointer: %d\n", pycode);

         PyEval_EvalCode(pycode, maindict, maindict);



More information about the Python-list mailing list