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:

----cut----
#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())
     {
       fclose(fp);
       return NULL;
     }

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

   return fp;
}


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

         Py_Initialize();
         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);
         Py_Finalize();

}

----cut----




More information about the Python-list mailing list