Round Trip: C to Python to C Module

Diez B. Roggisch deets at web.de
Fri Nov 19 14:25:49 EST 2010


Eric Frederich <eric.frederich at gmail.com> writes:

> I have a proprietary software PropSoft that I need to extend.
> They support extensions written in C that can link against PropLib to
> interact with the system.
>
> I have a Python C module that wraps a couple PropLib functions that I
> call PyProp.
>>From an interactive Python shell I can import PyProp and call a function.
> None of these functions really do anything outside the context of
> being logged into the PropSoft software; so all the functions fail
> when running from Python alone.
>
> To my amazement, I was able to run PyRun_SimpleString("import
> PyProp\nPyProp.some_function()") without setting PYTHONPATH or
> anything.  How this works, I don't know and I don't really care (at
> the moment anyway).
>
> The problem I'm having now is how do I return things from my Python
> script back to C?
> Ultimately I won't be hard coding python inside of PyRun_SimpleString
> but loading the script from a file.
> So, how do I return values back to C?  Python functions return values
> but running a python script?... doesn't that just have an exit status?
> Is there a mechanism for doing this?

You write an extension in C that embeds a Python-interpreter. That
interpreter then loads your script, and executes it. 

Let's say the PropSoft offers you three functions for a custom
extension.

void init();
int do_something(int);
void cleanup();

Then you write a C-extension that contains these three function calls,
and in init, you create a Python-interpreter and load your script. It
should offer a "do_something_in_python" method that takes an int and
returns one.

In do_something, you invoke the aforementioned do_something_in_python
function through the Python C-API as described.

In cleanup, you do what the function name says.

Possibly the use of elmer[1] makes the whole process easier.

[1]: http://wiki.python.org/moin/elmer

--

Diez



More information about the Python-list mailing list