Adding and running functions at runtime

Bjorn Pettersen BPettersen at NAREX.com
Wed Jun 12 14:54:02 EDT 2002


> From: John Dunn [mailto:jhndnn at yahoo.com] 
> 
> Hello-
> 
> I am currently embedding Python in my C++ application and 
> would like to add function 'scriplets' defined by strings and 
> then call them from C. Let me explain what I am trying to do -
> 
> 1. load a string that defines a function ( or functions )
> 2. get the function object for a defined function
> 3. call function with arguments
> 4. get return value and modified argument values
> 
> so the code might look something like
> 
> const char * funcs = 
> "def foo( arg1, arg2 )\n"
> "    arg2 = arg2\n"
> "def foo2( arg1, arg2 )\n"
> "    return arg1+arg2\n"
> 
> Mythical_PyLoad( funcs );
> PyObject* foo = Mythical_PyGet_Function( "foo" );
> PyObject* foo2 = Mythical_PyGet_Function( "foo2" );
> PyOjbect* args = some code here to create arguments
> // this should return the sume of the args
> PyObject* result = PyEval_CallObject( foo2, args ); 
> // this should modify the second arg
> PyObject* result = PyEval_CallObject( foo, args ); 
> 
> I have been able to load code using Py_CompileString, but 
> that appears to run inline code, and I couldn't get it to 
> return a value or modify something in the dictionary.

I'm working on something similar. The interface looks like e.g.:

        py::Namespace ns;
        NDate d(1970, 5, 2);
        ns.set("tmp", d);

        py::stmts(
            "def two():          \n"
            "    return 2        \n",
            ns);

        int result = py::expr("two() + tmp.getYear()", ns);

i.e. it uses a namespace to keep track of your function definitions and
you get values by assigning the result of py::expr() to the appropriate
type. I can send you the code if you'd like...

oh, and it also deals with SIP wrapped libraries :-)

-- bjorn





More information about the Python-list mailing list