C API Q I : calling Python methods from C

Martin v. Löwis loewis at informatik.hu-berlin.de
Sun Apr 14 08:31:35 EDT 2002


"Johan Hahn" <johahn at delta.telenordia.se> writes:

> I can't figure out how to call methods written in python from C
> using the low level API.

I could not quite figure out what your question is, but I interpret it
as "How do I do the following Python code with the C API"?

> /* b4 module */
> import code
> iii = code.InteractiveInterpreter()
> def runsource(code):
>     iii.runsource(code)


> You are supposed to read the class' dictionary for methods, convert
> a method to a function and call the function with the instance as
> the first parameter, right?

That sounds way to complicated. Here is what I would do

code = PyImport_ImportModule("code");
iii = PyObject_CallMethod(code, "InteractiveInterpreter", "");
runsource_result = PyObject_CallMethod(iii, "runsource",
                                       "i", 42);

assuming you want to pass the argument 42 to iii.runsource.

Don't forget to check for exceptions!

HTH,
Martin



More information about the Python-list mailing list