Embedding/Extending Python in/with C++: non-static members?

AnonMail2005 at gmail.com AnonMail2005 at gmail.com
Thu Jul 19 01:35:43 EDT 2007


On Jul 17, 12:24 pm, dmoore <damienlmo... at gmail.com> wrote:
> (I thought I'd follow up on this post so as not to send unsuspecting
> readers down a hopeless path)
>
> duh!
>
> I've obviously spent too much time with dynamic languages. The problem
> with what I'm trying to do is obvious: In C++ you simply can't pass
> pointers to call a particular instance of a C++ class method so there
> is no way to initialize the PyMethodDef with class methods instances.
> In other words, there is no callback mechanism built into the language
> and you are stuck with template based approaches, which obviously
> don't mesh very well with the Python/C API (without SWIG,
> Boost::Python etc).
>
> So to get a python interpreter instance to communicate with pre-
> existing dynamically allocated C++ objects, it looks like I need to
> implement some kind of lookup table approach. The static nature of the
> Python/C API is just too cumbersome for use with multiple interpreters
> and making me thing it might be better to embed just a sinlge
> interpreter inside my app and use multi-process communication with
> either pipes or sockets for the extra interpreters...

I'm doing a similar thing, and I would imagine others are also.

1. In a python file, set up wrapper functions that the python user
actually uses (e.g FunctionA).  Each function corresponds to a
particular C/C++ extension function that you are exposing (e.g.
CFunctionA).

2. Each wrapper function takes the same number of args as the C/C++
extension function except it adds one additional argument - the
interperter
identifier.

3. The interpreter identifier is just a global id (e.g. an integer)
that
is unique for each interpreter and is set before hand.  We set the id
by
first loading the wrapper function python file (in C/C++) and calling
a
predefined function that sets the id (you just pass the id as an
argument
to the function).

4. Now when you enter you C/C++ function you can find your object by
looking
it up in some predefined table using the id.  What we actually do is
not use
an integer but instead use a void pointer which is cast appropriately
once
inside C/C++.  This avoids the lookup.

Hope that helps.




More information about the Python-list mailing list