1 #===- common.py - Python LLVM Bindings -----------------------*- python -*--===#
3 # The LLVM Compiler Infrastructure
5 # This file is distributed under the University of Illinois Open Source
6 # License. See LICENSE.TXT for details.
8 #===------------------------------------------------------------------------===#
10 from ctypes import POINTER
11 from ctypes import c_void_p
12 from ctypes import cdll
22 c_object_p = POINTER(c_void_p)
24 class LLVMObject(object):
25 """Base class for objects that are backed by an LLVM data structure.
27 This class should never be instantiated outside of this package.
29 def __init__(self, ptr, ownable=True, disposer=None):
30 assert isinstance(ptr, c_object_p)
32 self._ptr = self._as_parameter_ = ptr
34 self._self_owned = True
35 self._ownable = ownable
36 self._disposer = disposer
38 self._owned_objects = []
40 def take_ownership(self, obj):
41 """Take ownership of another object.
43 When you take ownership of another object, you are responsible for
44 destroying that object. In addition, a reference to that object is
45 placed inside this object so the Python garbage collector will not
46 collect the object while it is still alive in libLLVM.
48 This method should likely only be called from within modules inside
51 assert isinstance(obj, LLVMObject)
53 self._owned_objects.append(obj)
54 obj._self_owned = False
57 """ctypes function that converts this object to a function parameter."""
58 return self._as_parameter_
61 if not hasattr(self, '_self_owned') or not hasattr(self, '_disposer'):
64 if self._self_owned and self._disposer:
67 class CachedProperty(object):
68 """Decorator that caches the result of a property lookup.
70 This is a useful replacement for @property. It is recommended to use this
71 decorator on properties that invoke C API calls for which the result of the
72 call will be idempotent.
74 def __init__(self, wrapped):
75 self.wrapped = wrapped
77 self.__doc__ = wrapped.__doc__
78 except: # pragma: no cover
81 def __get__(self, instance, instance_type=None):
85 value = self.wrapped(instance)
86 setattr(instance, self.wrapped.__name__, value)
91 # FIXME should probably have build system define absolute path of shared
92 # library at install time.
93 for lib in ['LLVM-3.1svn', 'libLLVM-3.1svn', 'LLVM', 'libLLVM']:
94 result = ctypes.util.find_library(lib)
101 """Obtain a reference to the llvm library."""
104 raise Exception('LLVM shared library not found!')
106 return cdll.LoadLibrary(lib)