Architecture:Python Module: Difference between revisions
m Fixed typos, added links |
m link added |
||
Line 1: | Line 1: | ||
This module includes the basic functionality essential for those objects that want to call | This module includes the basic functionality essential for those objects that want to call | ||
Python methods or need to be accessible within Python scripts. | Python methods or need to be accessible within [[Scripting:Contents|Python scripts]]. | ||
== SWIG support == | == SWIG support == |
Revision as of 18:52, 19 June 2005
This module includes the basic functionality essential for those objects that want to call Python methods or need to be accessible within Python scripts.
SWIG support
To allow passing an object from C++ to Python and vice versa, it must be wrapped in a PyObject by SWIG and unwrapped again later. Basically, SWIG stores a string representation of an objects pointer and the type information neccessary to call its methods. Therefore, each class that needs to be passed between the engine and Python scripts has to provide this type information, i.e. its class name. This is done by the method get_type_name, which can be generated by the GET_TYPE_NAME macro. Once it is present, wrapping and unwrapping can be handled automatically by pass_instance and retrieve_instance.
In order to make parts of the engine known to Python in the first place, they have to be added to the appropriate SWIG interface file residing in the py-wrappers/adonthell/ directory. Usually, including the header is enough, but in special cases, extra care has to be taken to avoid memory leaks or allow for in/out parameters. Details on this can be found in the SWIG manual.
Python Scripts and Methods
A wrapper around the Python C API is provided, to instanciate classes defined in Python scripts and call the methods they provide. If exclusive access to a python object is required, the script class can be used directly. It will always instanciate a new object. If that is not required, Python objects should be accessed via the pool. Each python object in the pool is only loaded once, thus reducing access time and memory footprint. Python objects that need their own context shouldn’t be used that way, however, to avoid the side effects of multiple consumers accessing the same instance.
It should be noted that Python callback used by event listeners do use the pool. Extra care needs to be taken when writing those callbacks. As a result, it is possible that way to pass data between different events, as long as their callbacks are methods of the same Python class.