The following example from Boost.Python v1.56 shows how to embed the Python 3.4.2 interpreter into your own application. Unfortunately that example does not work out of the box on my configuration with MSVC2013 under Windows 8.1. And I have not found 1 working complete example about embedding, at least none that is younger than 10 years or so.
I receive the following error running it: ImportError: 'embedded_hello' is not a built-in module
The code is here: http://pastebin.com/shTtdxT8
Any hints what I can do to let this run? And in general how to expose a c++ class in Python and vice versa?
The code is compiling with a Python 2 header configuration. When compiling with a Python 3 header configuration, the
boost/python/module_init.hpp
would have declared theembedded_hello
module's initialization function asPyInit_embedded_hello
rather thaninitembedded_hello
. I highly recommend verifying the proper header configuration, and performing a clean build of Boost.Python, as Boost.Python and modules built with the library need to use the same header configuration.Additionally, when adding modules to the built-in table, the
PyImport_AppendInittab()
calls need to occur beforePy_Initialize()
. ThePyImport_AppendInittab()
documentation explicitly states:Boost.Python uses the
BOOST_PYTHON_MODULE
macro to define a Python module. Within the body of the module, the current scope is the module itself. Thus, when C++ types are exposed via type wrappers, such as when a C++ classes is exposed to Python viaboost::python::class_
, the resulting Python class will be within the module defined byBOOST_PYTHON_MODULE
.On the other hand, user-defined types declared in Python are first-class objects. From a C++ perspective, they can be treated as though they are a factory function. Hence, to use a Python defined class in C++, one needs to get a handle to the class object, then instantiate an instance of a class by calling the class object.
Here is a complete minimal example demonstrating embedding a Python 3 interpreter that:
example
) that has been built directly into the binary and exposes a basic C++ class (spam_wrap
) to Python (example.Spam
) that has virtual function/dispatching with a default.example.Spam
).example.Spam
) within Python (example.PySpam
) and uses the resulting class.The program should run to completion without errors, resulting in the following output: