[C++-sig] Creating an instance of a python class derived from a C++ object from C++

Brian Hall bhall at midwaygames.com
Sat Jul 10 19:47:07 CEST 2004


Hello all,

Say I have the following:

class MyCppClass
{
public:
  virtual int SomeFunction(void) = 0;
};

struct MyCppClassWrap : public MyCppClass
{
  MyCppClassWrap(PyObject *self_)
    : self(self_)
  {}
  int SomeFunction(void) { return call_method<int>(self, "some_function"); }

  PyObject *self;
};

int call_SomeFunction(MyCppClass &c) { return c.SomeFunction(); }

BOOST_PYTHON_MODULE(MyPythonModule)
{
  class_<cState>("State", init<std::string>())
    .def("value", &cState::Value)
    .def("set_value", &cState::SetValue)
    .def("initial_value", &cState::InitialValue)
    .def("set_initial_value", &cState::SetInitialValue)
    .def("name", &cState::Name)
    .def("reset", &cState::Reset)
    .def("iterate", &cState::Iterate)
  ;
  def("call_some_function", call_SomeFunction);
};

Now say I want to dynamically create an instance of a python class derived 
from MyCppClass like so:

class MyPythonClass(MyCppClass):
  def SomeFunction(self):
    return 42

But I want to do this from C++, not Python... how would I do this?  Basically 
I want to be able to define new Python derived types of MyCppClass at runtime 
on the fly, and redefine them at will.  Say for instance the user of the 
application typed in the above declaration of MyPythonClass... and then later, 
updated that definition to return 43 instead, I want to be able to redefine 
the code for the class... if I did that, would I have to destroy the old 
instance and create a new one?  Any ideas?




More information about the Cplusplus-sig mailing list