|
| 1 | +/***************************************************************************** |
| 2 | +* |
| 3 | +* diffpy.srreal Complex Modeling Initiative |
| 4 | +* (c) 2016 Brookhaven Science Associates, |
| 5 | +* Brookhaven National Laboratory. |
| 6 | +* All rights reserved. |
| 7 | +* |
| 8 | +* File coded by: Pavol Juhas |
| 9 | +* |
| 10 | +* See AUTHORS.txt for a list of people who contributed. |
| 11 | +* See LICENSE.txt for license information. |
| 12 | +* |
| 13 | +****************************************************************************** |
| 14 | +* |
| 15 | +* Utilities for wrapping classes that derive from HasClassRegistry. |
| 16 | +* |
| 17 | +*****************************************************************************/ |
| 18 | + |
| 19 | +#ifndef SRREAL_REGISTRY_HPP_INCLUDED |
| 20 | +#define SRREAL_REGISTRY_HPP_INCLUDED |
| 21 | + |
| 22 | +#include <boost/python/object.hpp> |
| 23 | + |
| 24 | +namespace srrealmodule { |
| 25 | + |
| 26 | +/// template class for handling Python Wrapper classes in C++ class registry |
| 27 | +template <class T> |
| 28 | +class wrapper_registry_configurator |
| 29 | +{ |
| 30 | + typedef typename T::SharedPtr TSharedPtr; |
| 31 | + typedef typename T::SharedPtr::element_type* TPtr; |
| 32 | + |
| 33 | + public: |
| 34 | + |
| 35 | + // constructor |
| 36 | + wrapper_registry_configurator() : mcptr(0), mpyptr(0) { } |
| 37 | + |
| 38 | + // methods |
| 39 | + /// the fetch method should be called only from the wrapped method |
| 40 | + /// create() to remember pointers to the last Python object and |
| 41 | + /// the C++ instance that it wraps. |
| 42 | + TSharedPtr fetch(::boost::python::object& obj) const |
| 43 | + { |
| 44 | + TSharedPtr p = ::boost::python::extract<TSharedPtr>(obj); |
| 45 | + mcptr = p.get(); |
| 46 | + mpyptr = obj.ptr(); |
| 47 | + return p; |
| 48 | + } |
| 49 | + |
| 50 | + /// the setup function should be executed just once from the |
| 51 | + /// HasClassRegistry::setupRegisteredObject method in the wrapper |
| 52 | + /// class. This ensures the Python object in a prototype factory |
| 53 | + /// stays alive when the process is shut down. |
| 54 | + void setup(TSharedPtr ptr) const |
| 55 | + { |
| 56 | + assert(mcptr && mcptr == ptr.get()); |
| 57 | + ::boost::python::incref(mpyptr); |
| 58 | + mcptr = 0; |
| 59 | + mpyptr = 0; |
| 60 | + } |
| 61 | + |
| 62 | + private: |
| 63 | + |
| 64 | + // data |
| 65 | + mutable TPtr mcptr; |
| 66 | + mutable PyObject* mpyptr; |
| 67 | +}; |
| 68 | + |
| 69 | +} // namespace srrealmodule |
| 70 | + |
| 71 | +#endif // SRREAL_REGISTRY_HPP_INCLUDED |
0 commit comments