Embedding Python

Pau Freixes pfreixes at gmail.com
Tue Jul 1 14:25:18 CEST 2008


Hi

If PyImport_ExecCodeModule have a two parameteres and second parameter is
PyObject type  why you are make a call with a unsigned char value ?

If you search this function name into Google you will can found some
examples, use for example PyMarshal_ReadObjectFromString or
PyMarshal_ReadObjectFromFile

Bye

On Tue, Jul 1, 2008 at 11:36 AM, Marcin Krol <mrkafk at gmail.com> 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."
>
> Code:
>
> ---cut---
> #include <Python.h>
> #include <stdio.h>
> #include <stdlib.h>
> #include <syslog.h>
> #include <unistd.h>
>
>
> int load_file(char *fname, unsigned char** result)
> {
>  int size = 0;
>  FILE *f = fopen(fname, "rb");
>  if (f == NULL)
>  {
>  *result = NULL;
>  return -1;
>  }
>  fseek(f, 0, SEEK_END);
>  size = ftell(f);
>  *result = (unsigned char *) malloc(size+1);
>  fseek(f, 0, SEEK_SET);
>  size = fread(*result, sizeof(unsigned char), size, f);
>  return size;
> }
>
> int main(int argc, char **argv)
> {
>        int size;
>        unsigned char *python_code;
>        PyObject *mainobj;
>        size = load_file("multiply.pyc", &python_code);
>
>        Py_Initialize();
>        mainobj = PyImport_ExecCodeModule("multiply", (PyObject *)
> python_code);
>        Py_Finalize();
>
> }
> ---cut---
>
> Compiling it following way works fine:
>
> ${CC} testit.c -g -o testit -I/usr/include/python2.4 -lpython2.4 -lm
> -lutil -lpthread -ldl  -L/usr/lib/python2.4/config
>
>
> However, the damn thing crashes on this call:
>
> 33              mainobj = PyImport_ExecCodeModule("multiply", (PyObject
> *) python_code);
> (gdb) n
>
> Program received signal SIGSEGV, Segmentation fault.
> 0x0804e7f6 in PyImport_ExecCodeModuleEx ()
>
> The .pyc file woks just fine in Python interpreter:
>
>  import multiply
>>>> multiply.multiply()
>>>>
>>> The result of 12345 x 6789 : 83810205
> 83810205
>
>>
>>>>
>
> What I am doing wrong? Please help.
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Pau Freixes
Linux GNU/User
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080701/e7b6b5ae/attachment.html>


More information about the Python-list mailing list