In the previous chapter, we saw how to use C++ classes in Python by wrapping them with SWIG. But what about going the other way—using Python classes from other languages? It turns out that this is really just a matter of applying interfaces already shown.
Recall that Python scripts generate class instance objects by calling class objects as though they were functions. To do it from C (or C++), simply follow the same steps: import a class from a module (or elsewhere), build an arguments tuple, and call it to generate an instance using the same C API tools you use to call Python functions. Once you've got an instance, you can fetch attributes and methods with the same tools you use to fetch globals out of a module.
To illustrate how this works in practice, Example 23-12 defines a simple Python class in a module that we can utilize from C.
Example 23-12. PP3E\Integrate\Embed\ApiClients\module.py
# call this class from C to make objects class klass: def method(self, x, y): return "brave %s %s" % (x, y) # run me from C
This is nearly as simple as it gets, but it's enough to
illustrate the basics. As usual, make sure that this module is on your
Python search path (e.g., in the current directory, or one listed on
PYTHONPATH setting), or else
the import call to access it from C will fail, just as it would in a
Python script. Now, here is how you might make use of this Python
class from a Python program:
import module ...