Boost logo

Boost Users :

From: ALEX NG (alex_at_[hidden])
Date: 2007-08-20 13:02:17


HI
I would like to run a C++ program that can call a python code which is
stored as a *.py. so that if I make any changes inside *.py, my C++
program can get the results.
In my code, I have a class CppClass and an object created from this class
called cpp.
How can I pass this object to a *.py file and get the new results?

class CppClass {
public:
  int getNum() {
    return 8;
  }
 // int getNum2(){//
      //return 12;
  //}
};

#include "boost/python.hpp"

using namespace boost::python;

int main( int argc, char ** argv ) {

  try {
    Py_Initialize();

    object main_module((
      handle<>(borrowed(PyImport_AddModule("__main__")))));

    object main_namespace = main_module.attr("__dict__");
      // main_namespace["cpp"] = ptr(&cpp);

      main_namespace["CppClass"] = class_<CppClass>("CppClass")
                               .def("getNum",&CppClass::getNum);

      CppClass cpp;
      cpp.getNum();

      main_namespace["multiply"] = ptr(&cpp);

handle<> ignored(( PyRun_String( "print multiply.getNum() \n",
                                      Py_file_input,
                                      main_namespace.ptr(),
                                      main_namespace.ptr() ) ));

  } catch( error_already_set ) {
    PyErr_Print();
  }
}

multiply.py
def multiply(a,b):
    global c
    print "Will compute", a, "times", b
    c=c+(a*b)

    return c


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net