Scope issues when embedding/extending

Paul Prescod paul at prescod.net
Sun Mar 19 03:27:06 EST 2000


I think I can guess what C++ application this is. :)

lss at excosoft.se wrote:
> 
> I am trying to embed Python scripting in a C++ application in a way so
> that the script interpreter has direct access to object instances and
> variables in the host application. 

Python code cannot directly access C++ objects for much the same reasons
that one C++ compiler may not be able to directly access another C++
compiler's objects. There is no standard layout for C++ objects and even
if there were, Python virtual method calling is string name-based
whereas in C++ it is pointer based.

What you need to do is wrap your C++ objects in a layer of Python
objects. You can either do this "by hand" (it is not too hard -- easier
than the equivalent in Java which excosoft has already done) or you can
use a tool called "SWIG" which generates then for you (but you lose
control over some details of your interface).

> How do I avoid creating a new object instance in the
> interpreter, but rather reference an already existing one in the host
> application? 

You create a PyObject which has as one of its fields a reference to the
original object. Something like:

typedef struct {
	PyObject_HEAD
	XML_Parser *real_parser;
} PythonXMLParser;

Then you do basically the same thing for each of your methods. You
typically write a Python method for each C++ method and call from one to
the other. Since you have a relatively sophisticated system already and
it already has a scripting language there may be some underlying
infrastructure you can use that allows you to have *one* Python method
that can invoke any C++ method based on its string name. But you don't
get that "for free". Your C++ code must be organized so that a
string->pointer mapping is available at runtime.

> Does Python support this form of integration natively or do
> I have to go via COM or some other protocol? 

If you want, you could use COM on Windows. The virtue of COM is that it
does the wrapping and method dispatching for you. You could think of it
as the infrastructure I described for making string-based invocation
possible. Microsoft has already done the hard work for you but of course
it only works on Windows. Alternately, you could use CORBA, which works
on Unix, but you'll have to organize your C++ code in a CORBA-friendly
manner.

http://www.loria.fr/~galibert/texi/ilu/manual_5.html

When you use COM or CORBA you do lose some control over the details of
your interface again.

-- 
 Paul Prescod  - ISOGEN Consulting Engineer speaking for himself
If all you want is sleep, go to bed.
But if you want to dream, go to Barbados.
    - Timothy Findley, "Barbados: The Very Pineapple of Perfection"




More information about the Python-list mailing list