Embedding Python In a WINDOWS App - Help!!!!

Miki Tebeka miki.tebeka at zoran.com
Mon Jul 19 04:12:32 EDT 2004


Hello Tim,

> Unfortunately I have a situation where extensions in DLLs need to call
> functions which are native to the WINDOWS application. 
It's somewhere in the docs
(http://www.python.org/doc/2.3.4/ext/extending-with-embedding.html) but the
general scheme is:
1. Write a wrapper functions to the ones Python need to access.
2. Initialize the interperter.
3. Initialize the module containing the warpper functions.
4. In the Python script import the wrapping module and then use these
    functions.

Exmaple:
I have a simulator which is written in C++. I've decided to add a module
using Python. Below is a shortened version of what I did.

--- sim.cpp ---
/* read_memory wrapper */
static PyObject *
py_read_memory(PyObject *self, PyObject *args)
{
    unsigned addr;
    unsigned long value;

    if (!PyArg_ParseTuple(args, "I", &addr)) {
        return NULL;
    }
    
    value = read_memory(addr); /* Call simulator function */

    return PyLong_FromUnsignedLong(value);
}

static PyMethodDef SimMethods[] = {
    {"read_memory", py_read_memory, METH_VARARGS, "Read internal memory"},
    {NULL, NULL, 0, NULL}
};

static int
py_initialize()
{
    PyObject *module, *modname, *dict;

    Py_Initialize();
    Py_InitModule("sim", SimMethods); /* Initialize simulator module */
}

--- sim.cpp ---

This way "read_memory" is accesible by any script run from the embedded
interpreter.
Just do:
--- module.py ---
import sim
val = ream_memory(0x1000)
--- module.py ---

HTH.
Bye.
--
------------------------------------------------------------------------
Miki Tebeka <miki.tebeka at zoran.com>
http://tebeka.spymac.net
The only difference between children and adults is the price of the toys



More information about the Python-list mailing list