8.2 Embedding PyS60

There is not much change with respect to embedding Python from what is mentioned in the Python mainline document apart from the custom memory allocator which is explained later in this Section.

The following code snippet, which prints 'Hello World!' on the screen, demonstrates the embedding of Python interpreter in a C code:

The source file contents are as follows:

#include <Python.h>
/* This is a GCCE toolchain workaround needed when compiling with GCCE
   and using main() entry point */
#ifdef __GCCE__
#include <staticlibinit_gcce.h>

int main(void)

    SPy_SetAllocator(SPy_DLC_Alloc, SPy_DLC_Realloc, SPy_DLC_Free, NULL);
    PyRun_SimpleString("print 'Hello World!'");
    return 0;

The basic initialization function is Py_Initialize(). This initializes the table of loaded modules, and creates the fundamental modules __builtin__, __main__ and sys. It also initializes the module search path (sys.path). Py_Finalize() is called when the application is done with its use of Python and wants to free all memory allocated by Python.

PyS60 provides a DLC custom allocator which can be used instead of Python memory allocator. SPy_SetAllocator() is used for redirecting the allocator used by Python. The arguments to this function are the custom functions for allocating, reallocating, freeing the memory and a context pointer in that order. SPy_DLC_Init() is used for initializing the DLC custom allocator. SPy_DLC_Fini() is used for finalizing the DLC custom allocator and doing a memory cleanup. If you want to use your own custom allocator you will have to define the allocation, reallocation and free memory functions and pass the function names to SPy_SetAllocator().

For more information on embedding Python, refer Embedding Python in Another Application

The MMP file contents for the above source is as follows:

TARGET        helloworld.exe

SYSTEMINCLUDE    \epoc32\include\python25
SYSTEMINCLUDE    \epoc32\include\stdapis
SYSTEMINCLUDE    \epoc32\include

/* Using main() as entry point */

/* libc and euser are always needed when using main() entry point */
LIBRARY libc.lib
LIBRARY euser.lib
LIBRARY python25.lib

SOURCEPATH      ..\src
SOURCE          helloworld.cpp

See About this document... for information on suggesting changes.