
P1: JYS
c11 JWBK378-Fletcher April 24, 2009 8:17 Printer: Yet to come
Hybrid Python/C++ Pricing Systems 161
11.2 EXERCISING nth imm of year FROM C++
We turn our attention now to ‘embedding’ a Python interpreter in a C++ program. We have
seen how to call C++ code from Python. Here we aim to do the reverse: call Python code
from C++. To do this we use a mix of Python C API routines together with helper types and
functions in the Boost.Python library:
#include <boost/detail/lightweight test.hpp>
#include <boost/python.hpp>
#include <boost/date
time/gregorian/gregorian.hpp>
int main()
{
namespace bd = boost::date
time;
namespace bg = boost::gregorian;
namespace python = boost::python;
typedef bd::year
based generator<bg::date> ybd t;
Py
Initialise();
try
{
//extract the ppf.date
time.nth imm of year class
//object
python::object main
module = python::import(" main ");
python::object global(main
module.attr(" dict "));
python::object result =
python::exec("from ppf.date
time import *\n", global, global);
python::object nth
imm of year class = global["nth imm of year"];
//use the class object to create instances of
//nth
imm of year
python::object first
imm = nth imm of year class(bg::Mar);
python::object second
imm = nth imm of year class(bg::Jun);
python::object third
imm = nth imm of year class(bg::Sep);
python::object fourth
imm = nth imm of year class(bg::Dec);
//get references to boost date
time year based generators
//from ...