Boost logo

Boost Users :

Subject: [Boost-users] [Pyhton] (re)binding class instance in python object
From: Tamas.Ruszkai_at_[hidden]
Date: 2015-04-27 02:49:43


Hi,

I have a plain C++ class which I want to exposed to python. The pyhton
object accesses the C++ class via smart pointer.

class Sensor : public boost::enable_shared_from_this<Sensor>
{
public:
        Sensor(int port);
        ~Sensor()

        void Open();
        void SendCommand(const std::string& command);
        void Close();
private:
        int _port;
};

auto sensorClassTypeObject = boost::python::class_<Sensor, boost::
shared_ptr<Sensor>>("Sensor", boost::python::init<int>())
        .def("Open", &Sensor::Open)
        .def("SendCommand", &Sensor::SendCommand)
        .def("Close", &Sensor::Close);

The question is: if I already have one instance of the C++ class (in a
dependency injection container) then how can I create in the C++ part an
instance of the python wrapper so that it does not create a new instance
of Sensor, but uses my existing Sensor instance? Then I would put this
instance into one of the python modules (this part would be made in C++)
inside the python interpreter to be able to access it via script.

Something like that:

shared_ptr<Sensor> sensorInstance = DIContainer.Resolve<Sensor>();
boost::object pythonInstance = sensorClassTypeObject(sensorInstance);
pythonInterpreterWrapper.AddToModule("__main__", pythonInstance);

Best Regards,
Tamas



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