Calling local functions from the C API

Jon Parise jon at csh.rit.edu
Sun Nov 17 19:57:40 EST 2002


On Sun, Nov 17, 2002 at 09:02:17AM +0100, Martin v. Loewis wrote:

> Jon Parise <jon at csh.rit.edu> writes:
> 
> > def SomeFunction():
> >     pass
> > 
> > ... gets evaluated by PyRun_RunString().  Later on, I'd like to call
> > SomeFunction from C (embedded Python interpreter).
> > 
> > Is that still not possible without playing with stack frames and such?
> 
> Ah, so you have a char* that has Python source code, and you want to
> run a specific function in it.
> 
> For such questions, always ask yourself how you would achieve this
> effect in pure Python, and then you'll see how to do it in C.
> 
> In Python, you could write
> 
> d = {}
> exec sourcecode in d
> func = d['SomeFunction']
> func()
> 
> Now just do the same in C. Which of the four steps is unclear to you?
 
Thinks makes sense, I think (although I may have more questions when I
work on my actual implementation).

The one thing I note, however, is that I just can't execute arbitrary
blocks of code via PyRun_SimpleString() and expect to be able to
execute a function defined in one of those blocks of code again.
Instead, it looks like I'll need to use Py_CompileString() or similar
to maintain a code object.

Is that correct?

(This is the first time I've actually used this aspect of the Python C
API, so I thank you for your patience.)

-- 
Jon Parise (jon at csh.rit.edu)  ::  http://www.csh.rit.edu/~jon/




More information about the Python-list mailing list