All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
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 "pxr/external/boost/python/def_visitor.hpp"
20#include "pxr/external/boost/python/raw_function.hpp"
21
22#include <string>
23
24PXR_NAMESPACE_OPEN_SCOPE
25
26namespace Tf_PySingleton {
27
28namespace bp = pxr_boost::python;
29
30TF_API
31bp::object _DummyInit(bp::tuple const & /* args */,
32 bp::dict const & /* kw */);
33
34template <class T>
35TfWeakPtr<T> GetWeakPtr(T &t) {
36 return TfCreateWeakPtr(&t);
37}
38
39template <class T>
40TfWeakPtr<T> GetWeakPtr(T const &t) {
41 // cast away constness for python...
42 return TfConst_cast<TfWeakPtr<T> >(TfCreateWeakPtr(&t));
43}
44
45template <class T>
46TfWeakPtr<T> GetWeakPtr(TfWeakPtr<T> const &t) {
47 return t;
48}
49
50template <typename PtrType>
51PtrType _GetSingletonWeakPtr(bp::object const & /* classObj */) {
52 typedef typename PtrType::DataType Singleton;
53 return GetWeakPtr(Singleton::GetInstance());
54}
55
56TF_API
57std::string _Repr(bp::object const &self, std::string const &prefix);
58
59struct Visitor : bp::def_visitor<Visitor> {
60 explicit Visitor() {}
61
62 friend class bp::def_visitor_access;
63 template <typename CLS>
64 void visit(CLS &c) const {
65 typedef typename CLS::metadata::held_type PtrType;
66
67 // Singleton implies WeakPtr.
68 c.def(TfPyWeakPtr());
69
70 // Wrap __new__ to return a weak pointer to the singleton instance.
71 c.def("__new__", _GetSingletonWeakPtr<PtrType>).staticmethod("__new__");
72 // Make __init__ do nothing.
73 c.def("__init__", bp::raw_function(_DummyInit));
74 }
75};
76
77}
78
79TF_API
80Tf_PySingleton::Visitor TfPySingleton();
81
82PXR_NAMESPACE_CLOSE_SCOPE
83
84#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.