[C++-sig] returning PyObject * (unmodified) from embedded python back to c++

Ambrose Kofi Laing aklaing at gmail.com
Tue Mar 18 01:26:47 CET 2008


All good now, thought I'd just post the final version.

---- mymodule.cpp --------------------------------------------------------

#define MYTYPE object
#define MYDEFAULT object(0)

/*

#define MYTYPE string
#define MYDEFAULT ""

*/


#include <iostream>
#include <fstream>
#include <string>
using namespace std;

#include <boost/python.hpp>
using namespace boost::python;

struct Base
{
  Base() { s = MYDEFAULT ; }
  Base(MYTYPE input){ s = input; }
  virtual ~Base() {}
  virtual MYTYPE run() { return s; }
  virtual void   chg(MYTYPE input) { s = input; }
private:
  MYTYPE s;
};

struct BaseWrap : Base, wrapper<Base>
{
  BaseWrap() : Base() {}
  BaseWrap(MYTYPE input) : Base(input) {}

  MYTYPE run() {
    if (override run = this->get_override("run"))
      return run();
    return Base::run();
  }

  MYTYPE default_run() {
    return this->Base::run();
  }

  void chg(MYTYPE input) {
    if (override chg = this->get_override("chg"))
      chg(input);
    else
      Base::chg(input);
  }

  void default_chg(MYTYPE input) {
    this->Base::chg(input);
  }
};

typedef boost::shared_ptr<Base> BasePtr;

BasePtr g(new Base);

BasePtr get_g() {
  return g;
}

BasePtr set_g(BasePtr input_g) {
  BasePtr tmp;
  tmp = g;
  g = input_g;
  return tmp;
}

MYTYPE run_g() {
  MYTYPE tmp;
  tmp = g->run();
  return tmp;
}

void chg_g(MYTYPE input) {
  g->chg(input);
}

BOOST_PYTHON_MODULE(mymodule) {

  def("set_g", set_g);
  def("get_g", get_g);
  def("run_g", run_g);
  def("chg_g", chg_g);

  class_<BaseWrap, boost::noncopyable>("Base", init<>())
    .def(init<MYTYPE>())
    .def("run", &Base::run, &BaseWrap::default_run)
    .def("chg", &Base::chg, &BaseWrap::default_chg)
    ;

  register_ptr_to_python< BasePtr >();

}

---- test.py --------------------------------------------------------

#!/usr/bin/env python

from mymodule import *

class DerivedS( Base ):
    def run( self ):
        x = Base.run( self )
        return x+x

class DerivedO( Base ):
    def chg( self, val ):
        y = [1,
             1.0,
             'string',
             ['array'],
             ('tuple',)
            ][val]
        Base.chg( self, y )
    def run( self ):
        x = Base.run( self )
        return x+x # defined for all 5 types above.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20080317/4a428dfa/attachment.htm>


More information about the Cplusplus-sig mailing list