Loading...
Searching...
No Matches
pySingleton.h
1//
2// Copyright 2016 Pixar
3//
4// Licensed under the terms set forth in the LICENSE.txt file available at
5// https://openusd.org/license.
6//
7#ifndef PXR_BASE_TF_PY_SINGLETON_H
8#define PXR_BASE_TF_PY_SINGLETON_H
9
10#include "pxr/pxr.h"
11
12#include "pxr/base/tf/api.h"
14#include "pxr/base/tf/pyUtils.h"
15
17#include "pxr/base/tf/weakPtr.h"
18
19#include <boost/python/class.hpp>
20#include <boost/python/default_call_policies.hpp>
21#include <boost/python/def_visitor.hpp>
22#include <boost/python/raw_function.hpp>
23
24#include <functional>
25#include <string>
26
27PXR_NAMESPACE_OPEN_SCOPE
28
29namespace Tf_PySingleton {
30
31namespace bp = boost::python;
32
33TF_API
34bp::object _DummyInit(bp::tuple const & /* args */,
35 bp::dict const & /* kw */);
36
37template <class T>
38TfWeakPtr<T> GetWeakPtr(T &t) {
39 return TfCreateWeakPtr(&t);
40}
41
42template <class T>
43TfWeakPtr<T> GetWeakPtr(T const &t) {
44 // cast away constness for python...
45 return TfConst_cast<TfWeakPtr<T> >(TfCreateWeakPtr(&t));
46}
47
48template <class T>
49TfWeakPtr<T> GetWeakPtr(TfWeakPtr<T> const &t) {
50 return t;
51}
52
53template <typename PtrType>
54PtrType _GetSingletonWeakPtr(bp::object const & /* classObj */) {
55 typedef typename PtrType::DataType Singleton;
56 return GetWeakPtr(Singleton::GetInstance());
57}
58
59TF_API
60std::string _Repr(bp::object const &self, std::string const &prefix);
61
62struct Visitor : bp::def_visitor<Visitor> {
63 explicit Visitor(std::string const &reprPrefix = std::string()) :
64 _reprPrefix(reprPrefix) {}
65
66 friend class bp::def_visitor_access;
67 template <typename CLS>
68 void visit(CLS &c) const {
69 typedef typename CLS::metadata::held_type PtrType;
70
71 // Singleton implies WeakPtr.
72 c.def(TfPyWeakPtr());
73
74 // Wrap __new__ to return a weak pointer to the singleton instance.
75 c.def("__new__", _GetSingletonWeakPtr<PtrType>).staticmethod("__new__");
76 // Make __init__ do nothing.
77 c.def("__init__", bp::raw_function(_DummyInit));
78
79 // If they supplied a repr prefix, provide a repr implementation.
80 if (!_reprPrefix.empty())
81 c.def("__repr__",
82 make_function(std::bind(
83 _Repr, std::placeholders::_1, _reprPrefix),
84 bp::default_call_policies(),
85 boost::mpl::vector2<std::string,
86 bp::object const &>()));
87 }
88private:
89 std::string _reprPrefix;
90};
91
92}
93
94TF_API
95Tf_PySingleton::Visitor TfPySingleton();
96TF_API
97Tf_PySingleton::Visitor TfPySingleton(std::string const &reprPrefix);
98
99PXR_NAMESPACE_CLOSE_SCOPE
100
101#endif // PXR_BASE_TF_PY_SINGLETON_H
Miscellaneous Utilities for dealing with script.
Pointer storage with deletion detection.
Definition: weakPtr.h:128
Enables wrapping of Weak or Ref & Weak held types to python.
Manage a single instance of an object.
Pointer storage with deletion detection.