Extending an embeded Python

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Mikin von Flap

    #1

    Extending an embeded Python

    I'm trying to embed Python in a Windows exe, and extend it with some
    functions in the same program. So far I only add one function:
    <file.h>
    static PyObject* py_print( PyObject* self, PyObject* args ) {
    const char* msg;
    if( !PyArg_ParseTup le( args, "s", &msg ) )
    return 0;
    EventLog::log( msg );
    Py_INCREF( Py_None );
    return Py_None;
    }
    static PyMethodDef StoneAgeMethods[] = {
    { "log", py_print, METH_VARARGS, "Print a message to the log" },
    { 0, 0, 0, 0 } /* sentinel */
    };
    <file.cpp>
    int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE, LPSTR, int ) {
    EventLog::init( "con_dump.t xt" );
    Py_Initialize() ;
    EventLog::log( "Python version '%s'", Py_GetVersion() );
    PyObject* res0 = Py_InitModule( "stoneage", StoneAgeMethods );
    res1 = PyRun_SimpleStr ing( "stoneage.l og( \"test\" )\n" ); // FAIL
    res2 = PyRun_SimpleStr ing( "log( \"test\" )\n" ); // FAIL
    res3 = PyRun_SimpleStr ing( "print \"test\"\n" ); // OK
    Py_Finalize();
    }
    This compiles without problems, but when I run it I can't use the "log"
    function. Result res0 is a non-null object.
    As far as I can understand the "Extending and Embedding the Python
    Interpreter" doc, res1 should work but it doesn't!
    I'm a total newbie to Python, so any help appreciated :)


  • Fredrik Lundh

    #2
    Re: Extending an embeded Python

    Mikin von Flap wrote:
    [color=blue]
    > PyObject* res0 = Py_InitModule( "stoneage", StoneAgeMethods );
    > res1 = PyRun_SimpleStr ing( "stoneage.l og( \"test\" )\n" ); // FAIL
    > res2 = PyRun_SimpleStr ing( "log( \"test\" )\n" ); // FAIL
    > res3 = PyRun_SimpleStr ing( "print \"test\"\n" ); // OK
    > Py_Finalize();[/color]
    [color=blue]
    > This compiles without problems, but when I run it I can't use the "log"
    > function. Result res0 is a non-null object.
    > As far as I can understand the "Extending and Embedding the Python
    > Interpreter" doc, res1 should work but it doesn't![/color]

    compare and contrast:

    C:\Python24>pyt hon
    Python 2.4 (#60, Nov 30 2004, 11:49:19)[color=blue][color=green][color=darkred]
    >>> stoneage.log("h ello")[/color][/color][/color]
    Traceback (most recent call last):
    File "<stdin>", line 1, in ?
    NameError: name 'stoneage' is not defined[color=blue][color=green][color=darkred]
    >>> sys.platform[/color][/color][/color]
    Traceback (most recent call last):
    File "<stdin>", line 1, in ?
    NameError: name 'sys' is not defined[color=blue][color=green][color=darkred]
    >>> import sys
    >>> sys.platform[/color][/color][/color]
    'win32'

    </F>



    Comment

    Working...