[llvm.py] Make ObjectFile destructor work
[oota-llvm.git] / bindings / python / llvm / core.py
1 #===- core.py - Python LLVM Bindings -------------------------*- python -*--===#
2 #
3 #                     The LLVM Compiler Infrastructure
4 #
5 # This file is distributed under the University of Illinois Open Source
6 # License. See LICENSE.TXT for details.
7 #
8 #===------------------------------------------------------------------------===#
9
10 from .common import LLVMObject
11 from .common import get_library
12
13 from ctypes import POINTER
14 from ctypes import byref
15 from ctypes import c_char_p
16 from ctypes import c_void_p
17
18 __all__ = [
19     "lib",
20     "MemoryBufferRef",
21 ]
22
23 lib = get_library()
24
25 class MemoryBuffer(object):
26     """Represents an opaque memory buffer."""
27
28     def __init__(self, filename=None):
29         """Create a new memory buffer.
30
31         Currently, we support creating from the contents of a file at the
32         specified filename.
33         """
34         if filename is None:
35             raise Exception("filename argument must be defined")
36
37         memory = LLVMObject()
38         out = c_char_p(None)
39
40         result = lib.LLVMCreateMemoryBufferWithContentsOfFile(filename,
41                 byref(memory), byref(out))
42
43         if result:
44             raise Exception("Could not create memory buffer: %s" % out.value)
45
46         self._memory = memory
47         self._as_parameter_ = self._memory
48         self._owned = True
49
50     def __del__(self):
51         if self._owned:
52             lib.LLVMDisposeMemoryBuffer(self._memory)
53
54     def from_param(self):
55         return self._as_parameter_
56
57     def release_ownership(self):
58         self._owned = False
59
60
61 def register_library(library):
62     library.LLVMCreateMemoryBufferWithContentsOfFile.argtypes = [c_char_p,
63             POINTER(LLVMObject), POINTER(c_char_p)]
64     library.LLVMCreateMemoryBufferWithContentsOfFile.restype = bool
65
66     library.LLVMDisposeMemoryBuffer.argtypes = [c_void_p]
67
68 register_library(lib)