ROOT  6.07/01
Reference Guide
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
cppyy.py
Go to the documentation of this file.
1 """ Dynamic C++ bindings generator.
2 """
3 
4 import sys, string
5 
6 ### helper to get the version number from root-config
7 def get_version():
8  try:
9  import commands
10  stat, output = commands.getstatusoutput("root-config --version")
11  if stat == 0:
12  return output
13  except Exception:
14  pass
15  # semi-sensible default in case of failure ...
16  return "6.03/XY"
17 
18 ### PyPy has 'cppyy' builtin (if enabled, that is)
19 if 'cppyy' in sys.builtin_module_names:
20  _builtin_cppyy = True
21 
22  import imp
23  sys.modules[ __name__ ] = \
24  imp.load_module( 'cppyy', *(None, 'cppyy', ('', '', imp.C_BUILTIN) ) )
25  del imp
26 
27  _thismodule = sys.modules[ __name__ ]
28  _backend = _thismodule.gbl
29 
30  # custom behavior that is not yet part of PyPy's cppyy
31  def _CreateScopeProxy( self, name ):
32  return getattr( self, name )
33  type(_backend).CreateScopeProxy = _CreateScopeProxy
34 
35  def _LookupCppEntity( self, name ):
36  return getattr( self, name )
37  type(_backend).LookupCppEntity = _LookupCppEntity
38 
39  class _Double(float): pass
40  type(_backend).Double = _Double
41 
42  def _AddressOf( self, obj ):
43  import array
44  return array.array('L', [_thismodule.addressof( obj )] )
45  type(_backend).AddressOf = _AddressOf
46 
47  del _AddressOf, _Double, _LookupCppEntity, _CreateScopeProxy
48 
49 else:
50  _builtin_cppyy = False
51 
52  # load PyROOT C++ extension module, special case for linux and Sun
53  needsGlobal = ( 0 <= sys.platform.find( 'linux' ) ) or\
54  ( 0 <= sys.platform.find( 'sunos' ) )
55  if needsGlobal:
56  # change dl flags to load dictionaries from pre-linked .so's
57  dlflags = sys.getdlopenflags()
58  sys.setdlopenflags( 0x100 | 0x2 ) # RTLD_GLOBAL | RTLD_NOW
59 
60  import libPyROOT as _backend
61 
62  # reset dl flags if needed
63  if needsGlobal:
64  sys.setdlopenflags( dlflags )
65  del needsGlobal
66 
67 # PyCintex tests rely on this, but they should not:
68 sys.modules[ __name__ ].libPyROOT = _backend
69 
70 if not _builtin_cppyy:
71  _backend.SetMemoryPolicy( _backend.kMemoryStrict )
72 
73 #--- Enable Autoloading ignoring possible error for the time being
74 try: _backend.gInterpreter.EnableAutoLoading()
75 except: pass
76 
77 ### -----------------------------------------------------------------------------
78 ### -- metaclass helper from six ------------------------------------------------
79 ### -- https://bitbucket.org/gutworth/six/src/8a545f4e906f6f479a6eb8837f31d03731597687/six.py?at=default#cl-800
80 #
81 # Copyright (c) 2010-2015 Benjamin Peterson
82 #
83 # Permission is hereby granted, free of charge, to any person obtaining a copy
84 # of this software and associated documentation files (the "Software"), to deal
85 # in the Software without restriction, including without limitation the rights
86 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
87 # copies of the Software, and to permit persons to whom the Software is
88 # furnished to do so, subject to the following conditions:
89 #
90 # The above copyright notice and this permission notice shall be included in all
91 # copies or substantial portions of the Software.
92 #
93 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
94 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
95 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
96 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
97 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
98 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
99 # SOFTWARE.
100 
101 def with_metaclass(meta, *bases):
102  """Create a base class with a metaclass."""
103  # This requires a bit of explanation: the basic idea is to make a dummy
104  # metaclass for one level of class instantiation that replaces itself with
105  # the actual metaclass.
106  class metaclass(meta):
107 
108  def __new__(cls, name, this_bases, d):
109  return meta(name, bases, d)
110  return type.__new__(metaclass, 'temporary_class', (), {})
111 
112 ### -----------------------------------------------------------------------------
113 
114 ### template support ------------------------------------------------------------
115 if not _builtin_cppyy:
116  class Template:
117  def __init__( self, name ):
118  self.__name__ = name
119 
120  def __repr__(self):
121  return "<cppyy.Template '%s' object at %s>" % (self.__name__, hex(id(self)))
122 
123  def __call__( self, *args ):
124  newargs = [ self.__name__[ 0 <= self.__name__.find( 'std::' ) and 5 or 0:] ]
125  for arg in args:
126  if type(arg) == str:
127  arg = ','.join( map( lambda x: x.strip(), arg.split(',') ) )
128  newargs.append( arg )
129  result = _backend.MakeRootTemplateClass( *newargs )
130 
131  # special case pythonization (builtin_map is not available from the C-API)
132  if 'push_back' in result.__dict__:
133  def iadd( self, ll ):
134  [ self.push_back(x) for x in ll ]
135  return self
136 
137  result.__iadd__ = iadd
138 
139  return result
140 
141  _backend.Template = Template
142 
143 
144 #--- LoadDictionary function and aliases -----------------------------
145 def loadDictionary(name):
146  # prepend "lib"
147  if sys.platform != 'win32' and name[:3] != 'lib':
148  name = 'lib' + name
149  sc = _backend.gSystem.Load(name)
150  if sc == -1: raise RuntimeError("Error Loading dictionary")
151 loadDict = loadDictionary
152 
154  sc = _backend.gSystem.Load(name)
155 
156 
157 #--- Other functions needed -------------------------------------------
158 if not _builtin_cppyy:
159  class _ns_meta( type ):
160  def __getattr__( cls, name ):
161  try:
162  attr = _backend.LookupCppEntity( name )
163  except TypeError as e:
164  raise AttributeError(str(e))
165  if type(attr) is _backend.PropertyProxy:
166  setattr( cls.__class__, name, attr )
167  return attr.__get__(cls)
168  setattr( cls, name, attr )
169  return attr
170 
171  class _stdmeta( type ):
172  def __getattr__( cls, name ): # for non-templated classes in std
173  try:
174  klass = _backend.CreateScopeProxy( name, cls )
175  except TypeError as e:
176  raise AttributeError(str(e))
177  setattr( cls, name, klass )
178  return klass
179 
181  class std( with_metaclass( _stdmeta, object ) ):
182  stlclasses = ( 'complex', 'pair', \
183  'deque', 'list', 'queue', 'stack', 'vector', 'map', 'multimap', 'set', 'multiset' )
184 
185  for name in stlclasses:
186  locals()[ name ] = Template( 'std::%s' % name )
187 
188  string = _backend.CreateScopeProxy( 'string' )
189 
190 else:
191  _global_cpp = _backend
192 
193 def Namespace( name ):
194  if not name:
195  return _global_cpp
196  try:
197  return _backend.LookupCppEntity( name )
198  except AttributeError:
199  pass
200  # to help auto-loading, simply declare the namespace
201  _backend.gInterpreter.Declare( 'namespace %s {}' % name )
202  return _backend.LookupCppEntity( name )
203 makeNamespace = Namespace
204 
205 def makeClass( name ) :
206  return _backend.CreateScopeProxy( name )
207 
208 def addressOf( obj ) : # Cintex-style
209  return _backend.AddressOf( obj )[0]
210 addressof = _backend.addressof # cppyy-style
211 
213  TClassTable = makeClass( 'TClassTable' )
215  classes = []
216  while True :
217  c = TClassTable.Next()
218  if c : classes.append( c )
219  else : break
220  return classes
221 
222 def add_smart_pointer(typename):
223  """Add a smart pointer to the list of known smart pointer types.
224  """
225  _backend.AddSmartPtrType(typename)
226 
227 #--- Global namespace and global objects -------------------------------
228 gbl = _global_cpp
229 sys.modules['cppyy.gbl'] = gbl
230 NULL = 0
231 class double(float): pass
232 class short(int): pass
233 class long_int(int): pass
234 class unsigned_short(int): pass
235 class unsigned_int(int): pass
236 class unsigned_long(int): pass
237 
238 #--- Copy over locally defined names ------------------------------------
239 if _builtin_cppyy:
240  for name in dir():
241  if name[0] != '_': setattr( _thismodule, name, eval(name) )
242 
243 #--- Compatibility ------------------------------------------------------
244 if not _builtin_cppyy:
245  bind_object = _backend.BindObject
246 
247 #--- Pythonization factories --------------------------------------------
248 import _pythonization
249 _pythonization._set_backend( _backend )
250 from _pythonization import *
251 del _pythonization
unsigned int hex
Definition: math.cpp:442
def _LookupCppEntity
Definition: cppyy.py:35
def __getattr__
Definition: cppyy.py:160
def __getattr__
Definition: cppyy.py:172
def __repr__
Definition: cppyy.py:120
def _AddressOf
Definition: cppyy.py:42
def __init__
Definition: cppyy.py:117
def _CreateScopeProxy
Definition: cppyy.py:31
static void Init()
def __call__
Definition: cppyy.py:123
def Namespace
Definition: cppyy.py:193
def with_metaclass
– metaclass helper from six ------------------------------------------—— – https://bitbucket.org/gutworth/six/src/8a545f4e906f6f479a6eb8837f31d03731597687/six.py?at=default#cl-800
Definition: cppyy.py:101
XFontStruct * id
Definition: TGX11.cxx:108
def load_reflection_info
Definition: cppyy.py:153
def get_version
helper to get the version number from root-config
Definition: cppyy.py:7
def loadDictionary
Definition: cppyy.py:145
static char * Next()
Returns next class from sorted class table.
def addressOf
Definition: cppyy.py:208
int type
Definition: TGX11.cxx:120
void dir(char *path=0)
Definition: rootalias.C:30
def add_smart_pointer
Definition: cppyy.py:222
def makeClass
Definition: cppyy.py:205
def getAllClasses
Definition: cppyy.py:212