| 1 |
"""Generate a Python ctypes wrapper file for a header file. |
| 2 |
|
| 3 |
Usage example:: |
| 4 |
wrap.py -lGL -oGL.py /usr/include/GL/gl.h |
| 5 |
|
| 6 |
>>> from GL import * |
| 7 |
|
| 8 |
""" |
| 9 |
from __future__ import annotations |
| 10 |
import sys |
| 11 |
import textwrap |
| 12 |
|
| 13 |
from ctypesparser import * |
| 14 |
|
| 15 |
|
| 16 |
class CtypesWrapper(CtypesParser, CtypesTypeVisitor): |
| 17 |
file=None |
| 18 |
def begin_output(self, output_file, library, link_modules=(), |
| 19 |
emit_filenames=(), all_headers=False): |
| 20 |
self.library = library |
| 21 |
self.file = output_file |
| 22 |
self.all_names = [] |
| 23 |
self.known_types = {} |
| 24 |
self.structs = set() |
| 25 |
self.enums = set() |
| 26 |
self.emit_filenames = emit_filenames |
| 27 |
self.all_headers = all_headers |
| 28 |
|
| 29 |
self.linked_symbols = {} |
| 30 |
for name in link_modules: |
| 31 |
module = __import__(name, globals(), locals(), ['foo']) |
| 32 |
for symbol in dir(module): |
| 33 |
if symbol not in self.linked_symbols: |
| 34 |
self.linked_symbols[symbol] = '%s.%s' % (name, symbol) |
| 35 |
self.link_modules = link_modules |
| 36 |
|
| 37 |
self.print_preamble() |
| 38 |
self.print_link_modules_imports() |
| 39 |
|
| 40 |
def wrap(self, filename, source=None): |
| 41 |
assert self.file, 'Call begin_output first' |
| 42 |
self.parse(filename, source) |
| 43 |
|
| 44 |
def end_output(self): |
| 45 |
self.print_epilogue() |
| 46 |
self.file = None |
| 47 |
|
| 48 |
def does_emit(self, symbol, filename): |
| 49 |
return self.all_headers or filename in self.emit_filenames |
| 50 |
|
| 51 |
def print_preamble(self): |
| 52 |
import textwrap |
| 53 |
print(textwrap.dedent(""" |
| 54 |
'''Wrapper for {library} |
| 55 |
|
| 56 |
Generated with: |
| 57 |
{argv} |
| 58 |
|
| 59 |
Do not modify this file. |
| 60 |
''' |
| 61 |
import ctypes |
| 62 |
from ctypes import * |
| 63 |
|
| 64 |
import pyglet.lib |
| 65 |
|
| 66 |
_lib = pyglet.lib.load_library({library!r}) |
| 67 |
|
| 68 |
_int_types = (c_int16, c_int32) |
| 69 |
if hasattr(ctypes, 'c_int64'): |
| 70 |
# Some builds of ctypes apparently do not have c_int64 |
| 71 |
# defined; it's a pretty good bet that these builds do not |
| 72 |
# have 64-bit pointers. |
| 73 |
_int_types += (ctypes.c_int64,) |
| 74 |
for t in _int_types: |
| 75 |
if sizeof(t) == sizeof(c_size_t): |
| 76 |
c_ptrdiff_t = t |
| 77 |
|
| 78 |
class c_void(Structure): |
| 79 |
# c_void_p is a buggy return type, converting to int, so |
| 80 |
# POINTER(None) == c_void_p is actually written as |
| 81 |
# POINTER(c_void), so it can be treated as a real pointer. |
| 82 |
_fields_ = [('dummy', c_int)] |
| 83 |
|
| 84 |
""".format( |
| 85 |
library=self.library, |
| 86 |
argv=' '.join(sys.argv), |
| 87 |
)).lstrip(), file=self.file) |
| 88 |
|
| 89 |
def print_link_modules_imports(self) -> None: |
| 90 |
for name in self.link_modules: |
| 91 |
print(f'import {name}', file=self.file) |
| 92 |
print(file=self.file) |
| 93 |
|
| 94 |
def print_epilogue(self) -> None: |
| 95 |
print(file=self.file) |
| 96 |
print('\n'.join(textwrap.wrap( |
| 97 |
'__all__ = [{}]'.format(', '.join([repr(n) for n in self.all_names])), |
| 98 |
width=78, |
| 99 |
break_long_words=False)), file=self.file) |
| 100 |
|
| 101 |
def handle_ctypes_constant(self, name, value, filename, lineno) -> None: |
| 102 |
if self.does_emit(name, filename): |
| 103 |
print(f'{name} = {value!r}', end=' ', file=self.file) |
| 104 |
print('\t# %s:%d' % (filename, lineno), file=self.file) |
| 105 |
self.all_names.append(name) |
| 106 |
|
| 107 |
def handle_ctypes_type_definition(self, name, ctype, filename, lineno) -> None: |
| 108 |
if self.does_emit(name, filename): |
| 109 |
self.all_names.append(name) |
| 110 |
if name in self.linked_symbols: |
| 111 |
print(f'{name} = {self.linked_symbols[name]}', file=self.file) |
| 112 |
else: |
| 113 |
ctype.visit(self) |
| 114 |
self.emit_type(ctype) |
| 115 |
print(f'{name} = {ctype!s}', end=' ', file=self.file) |
| 116 |
print('\t# %s:%d' % (filename, lineno), file=self.file) |
| 117 |
else: |
| 118 |
self.known_types[name] = (ctype, filename, lineno) |
| 119 |
|
| 120 |
def emit_type(self, t) -> None: |
| 121 |
t.visit(self) |
| 122 |
for s in t.get_required_type_names(): |
| 123 |
if s in self.known_types: |
| 124 |
if s in self.linked_symbols: |
| 125 |
print(f'{s} = {self.linked_symbols[s]}', file=self.file) |
| 126 |
else: |
| 127 |
s_ctype, s_filename, s_lineno = self.known_types[s] |
| 128 |
s_ctype.visit(self) |
| 129 |
|
| 130 |
self.emit_type(s_ctype) |
| 131 |
print(f'{s} = {s_ctype!s}', end=' ', file=self.file) |
| 132 |
print('\t# %s:%d' % (s_filename, s_lineno), file=self.file) |
| 133 |
del self.known_types[s] |
| 134 |
|
| 135 |
def visit_struct(self, struct) -> None: |
| 136 |
if struct.tag in self.structs: |
| 137 |
return |
| 138 |
self.structs.add(struct.tag) |
| 139 |
|
| 140 |
base = {True: 'Union', False: 'Structure'}[struct.is_union] |
| 141 |
print(f'class struct_{struct.tag}({base}):', file=self.file) |
| 142 |
print(' __slots__ = [', file=self.file) |
| 143 |
if not struct.opaque: |
| 144 |
for m in struct.members: |
| 145 |
print(f" '{m[0]}',", file=self.file) |
| 146 |
print(' ]', file=self.file) |
| 147 |
|
| 148 |
|
| 149 |
|
| 150 |
for _name, typ in struct.members: |
| 151 |
self.emit_type(typ) |
| 152 |
|
| 153 |
print(f'struct_{struct.tag}._fields_ = [', file=self.file) |
| 154 |
if struct.opaque: |
| 155 |
print(" ('_opaque_struct', c_int)", file=self.file) |
| 156 |
self.structs.remove(struct.tag) |
| 157 |
else: |
| 158 |
for m in struct.members: |
| 159 |
print(f" ('{m[0]}', {m[1]}),", file=self.file) |
| 160 |
print(']', file=self.file) |
| 161 |
print(file=self.file) |
| 162 |
|
| 163 |
def visit_enum(self, enum) -> None: |
| 164 |
if enum.tag in self.enums: |
| 165 |
return |
| 166 |
self.enums.add(enum.tag) |
| 167 |
|
| 168 |
print(f'enum_{enum.tag} = c_int', file=self.file) |
| 169 |
for name, value in enum.enumerators: |
| 170 |
self.all_names.append(name) |
| 171 |
print('%s = %d' % (name, value), file=self.file) |
| 172 |
|
| 173 |
def handle_ctypes_function(self, name, restype, argtypes, filename, lineno) -> None: |
| 174 |
if self.does_emit(name, filename): |
| 175 |
|
| 176 |
|
| 177 |
self.emit_type(restype) |
| 178 |
for a in argtypes: |
| 179 |
self.emit_type(a) |
| 180 |
|
| 181 |
self.all_names.append(name) |
| 182 |
print('# %s:%d' % (filename, lineno), file=self.file) |
| 183 |
print(f'{name} = _lib.{name}', file=self.file) |
| 184 |
print(f'{name}.restype = {restype!s}', file=self.file) |
| 185 |
print('{}.argtypes = [{}]'.format(name, ', '.join([str(a) for a in argtypes])), file=self.file) |
| 186 |
print(file=self.file) |
| 187 |
|
| 188 |
def handle_ctypes_variable(self, name, ctype, filename, lineno) -> None: |
| 189 |
|
| 190 |
|
| 191 |
|
| 192 |
pass |
| 193 |
|
| 194 |
def main(*argv) -> None: |
| 195 |
import optparse |
| 196 |
import os.path |
| 197 |
import sys |
| 198 |
|
| 199 |
usage = 'usage: %prog [options] <header.h>' |
| 200 |
op = optparse.OptionParser(usage=usage) |
| 201 |
op.add_option('-o', '--output', dest='output', |
| 202 |
help='write wrapper to FILE', metavar='FILE') |
| 203 |
op.add_option('-l', '--library', dest='library', |
| 204 |
help='link to LIBRARY', metavar='LIBRARY') |
| 205 |
op.add_option('-D', '--define', dest='defines', default=[], |
| 206 |
help='define token NAME=VALUE', action='append') |
| 207 |
op.add_option('-i', '--include-file', action='append', dest='include_files', |
| 208 |
help='assume FILE is iincluded', metavar='FILE', |
| 209 |
default=[]) |
| 210 |
op.add_option('-I', '--include-dir', action='append', dest='include_dirs', |
| 211 |
help='add DIR to include search path', metavar='DIR', |
| 212 |
default=[]) |
| 213 |
op.add_option('-m', '--link-module', action='append', dest='link_modules', |
| 214 |
help='use symbols from MODULE', metavar='MODULE', |
| 215 |
default=[]) |
| 216 |
op.add_option('-a', '--all-headers', action='store_true', |
| 217 |
dest='all_headers', |
| 218 |
help='include symbols from all headers', default=False) |
| 219 |
|
| 220 |
(options, args) = op.parse_args(list(argv[1:])) |
| 221 |
if len(args) < 1: |
| 222 |
print('No header files specified.', file=sys.stderr) |
| 223 |
sys.exit(1) |
| 224 |
headers = args |
| 225 |
|
| 226 |
if options.library is None: |
| 227 |
options.library = os.path.splitext(headers[0])[0] |
| 228 |
if options.output is None: |
| 229 |
options.output = f'{options.library}.py' |
| 230 |
|
| 231 |
wrapper = CtypesWrapper() |
| 232 |
wrapper.begin_output(open(options.output, 'w'), |
| 233 |
library=options.library, |
| 234 |
emit_filenames=headers, |
| 235 |
link_modules=options.link_modules, |
| 236 |
all_headers=options.all_headers) |
| 237 |
wrapper.preprocessor_parser.include_path += options.include_dirs |
| 238 |
for define in options.defines: |
| 239 |
name, value = define.split('=') |
| 240 |
wrapper.preprocessor_parser.define(name, value) |
| 241 |
for file in options.include_files: |
| 242 |
wrapper.wrap(file) |
| 243 |
for header in headers: |
| 244 |
wrapper.wrap(header) |
| 245 |
wrapper.end_output() |
| 246 |
|
| 247 |
print(f'Wrapped to {options.output}') |
| 248 |
|
| 249 |
if __name__ == '__main__': |
| 250 |
main(*sys.argv) |