<commit_before>#!/usr/bin/env python

'''Generate a Python ctypes wrapper file for a header file.

Usage example::
    wrap.py -lGL -oGL.py /usr/include/GL/gl.h

    >>> from GL import *

'''

__docformat__ = 'restructuredtext'
__version__ = '$Id: wrap.py 738 2007-03-12 04:53:42Z Alex.Holkner $'

from ctypesparser import *
import textwrap
import sys, re
from ctypes import CDLL, RTLD_LOCAL, RTLD_GLOBAL, c_byte
from ctypes.util import find_library

def load_library(name, mode=RTLD_LOCAL):
    if os.name == "nt":
        return CDLL(name, mode=mode)
    path = find_library(name)
    if path is None:
        # Maybe 'name' is not a library name in the linker style,
        # give CDLL a last chance to find the library.
        path = name
    return CDLL(path, mode=mode)

class CtypesWrapper(CtypesParser, CtypesTypeVisitor):
    file=None
    def begin_output(self, output_file, library, link_modules=(), 
                     emit_filenames=(), all_headers=False,
                     include_symbols=None, exclude_symbols=None):
        self.library = library
        self.file = output_file
        self.all_names = []
        self.known_types = {}
        self.structs = set()
        self.opaque_structs = set()
        self.enums = set()
        self.emit_filenames = emit_filenames
        self.all_headers = all_headers
        self.include_symbols = None
        self.exclude_symbols = None
        if include_symbols:
            self.include_symbols = re.compile(include_symbols)
        if exclude_symbols:
            self.exclude_symbols = re.compile(exclude_symbols)

        self.linked_symbols = {}
        for name in link_modules:
            module = __import__(name, globals(), locals(), ['foo'])
            for symbol in dir(module):
                if symbol not in self.linked_symbols:
                    self.linked_symbols[symbol] = '%s.%s' % (name, symbol)
        self.link_modules = link_modules

        self.print_preamble()
        self.print_link_modules_imports()

    def wrap(self, filename, source=None):
        assert self.file, 'Call begin_output first'
        self.parse(filename, source)

    def end_output(self):
        self.print_epilogue()
        self.file = None

    def does_emit(self, symbol, filename, restype=None, argtypes=[]):

        # Skip any functions which mention excluded types
        if self.exclude_symbols:
            for a in [symbol, restype] + argtypes:
                if a and self.exclude_symbols.match(str(a)):
                    return

        if self.include_symbols and not re.match(self.include_symbols, symbol):
            return False

        return self.all_headers or filename in self.emit_filenames

    def print_preamble(self):
        import textwrap
        import time
        print >> self.file, textwrap.dedent("""
            '''Wrapper for %(library)s
            
            Generated with:
            %(argv)s
            
            Do not modify this file.
            '''

            __docformat__ =  'restructuredtext'
            __version__ = '$Id: wrap.py 738 2007-03-12 04:53:42Z Alex.Holkner $'

            import ctypes
            from ctypes import *

            _int_types = (c_int16, c_int32)
            if hasattr(ctypes, 'c_int64'):
                # Some builds of ctypes apparently do not have c_int64
                # defined; it's a pretty good bet that these builds do not
                # have 64-bit pointers.
                _int_types += (ctypes.c_int64,)
            for t in _int_types:
                if sizeof(t) == sizeof(c_size_t):
                    c_ptrdiff_t = t

            class c_void(Structure):
                # c_void_p is a buggy return type, converting to int, so
                # POINTER(None) == c_void_p is actually written as
                # POINTER(c_void), so it can be treated as a real pointer.
                _fields_ = [('dummy', c_int)]

            _libs = {}

            # As of ctypes 1.0, ctypes does not support custom error-checking
            # functions on callbacks, nor does it support custom datatypes on
            # callbacks, so we must ensure that all callbacks return
            # primitive datatypes.
            #
            # Non-primitive return values wrapped with UNCHECKED won't be
            # typechecked, and will be converted to c_void_p.
            def UNCHECKED(type):
                if (hasattr(type, "_type_") and isinstance(type._type_, str)
                    and type._type_ != "P"):
                    return type
                else:
                    return c_void_p
        """ % {
            'library': str(self.library),
            'date': time.ctime(),
            'class': self.__class__.__name__,
            'argv': ' '.join(sys.argv),
        }).lstrip()
        self.loaded_libraries = []
        for library in self.library:
            lib = load_library(library)
            if lib:
                self.loaded_libraries.append(lib)
                print >>self.file, textwrap.dedent("""
                    _libs[%r] = cdll.LoadLibrary(%r)
                """ % (lib._name, lib._name))

    def print_link_modules_imports(self):
        for name in self.link_modules:
            print >> self.file, 'from %s import *' % name
        print >> self.file

    def print_epilogue(self):<commit_msg>* wrap.py: Use RTLD_GLOBAL to load libraries, instead of RTLD_LOCAL, so as   to share symbols between libraries on Mac OS X.<commit_after>#!/usr/bin/env python

'''Generate a Python ctypes wrapper file for a header file.

Usage example::
    wrap.py -lGL -oGL.py /usr/include/GL/gl.h

    >>> from GL import *

'''

__docformat__ = 'restructuredtext'
__version__ = '$Id: wrap.py 738 2007-03-12 04:53:42Z Alex.Holkner $'

from ctypesparser import *
import textwrap
import sys, re
from ctypes import CDLL, RTLD_GLOBAL, c_byte
from ctypes.util import find_library

def load_library(name, mode=RTLD_GLOBAL):
    if os.name == "nt":
        return CDLL(name, mode=mode)
    path = find_library(name)
    if path is None:
        # Maybe 'name' is not a library name in the linker style,
        # give CDLL a last chance to find the library.
        path = name
    return CDLL(path, mode=mode)

class CtypesWrapper(CtypesParser, CtypesTypeVisitor):
    file=None
    def begin_output(self, output_file, library, link_modules=(), 
                     emit_filenames=(), all_headers=False,
                     include_symbols=None, exclude_symbols=None):
        self.library = library
        self.file = output_file
        self.all_names = []
        self.known_types = {}
        self.structs = set()
        self.opaque_structs = set()
        self.enums = set()
        self.emit_filenames = emit_filenames
        self.all_headers = all_headers
        self.include_symbols = None
        self.exclude_symbols = None
        if include_symbols:
            self.include_symbols = re.compile(include_symbols)
        if exclude_symbols:
            self.exclude_symbols = re.compile(exclude_symbols)

        self.linked_symbols = {}
        for name in link_modules:
            module = __import__(name, globals(), locals(), ['foo'])
            for symbol in dir(module):
                if symbol not in self.linked_symbols:
                    self.linked_symbols[symbol] = '%s.%s' % (name, symbol)
        self.link_modules = link_modules

        self.print_preamble()
        self.print_link_modules_imports()

    def wrap(self, filename, source=None):
        assert self.file, 'Call begin_output first'
        self.parse(filename, source)

    def end_output(self):
        self.print_epilogue()
        self.file = None

    def does_emit(self, symbol, filename, restype=None, argtypes=[]):

        # Skip any functions which mention excluded types
        if self.exclude_symbols:
            for a in [symbol, restype] + argtypes:
                if a and self.exclude_symbols.match(str(a)):
                    return

        if self.include_symbols and not re.match(self.include_symbols, symbol):
            return False

        return self.all_headers or filename in self.emit_filenames

    def print_preamble(self):
        import textwrap
        import time
        print >> self.file, textwrap.dedent("""
            '''Wrapper for %(library)s
            
            Generated with:
            %(argv)s
            
            Do not modify this file.
            '''

            __docformat__ =  'restructuredtext'
            __version__ = '$Id: wrap.py 738 2007-03-12 04:53:42Z Alex.Holkner $'

            import ctypes
            from ctypes import *

            _int_types = (c_int16, c_int32)
            if hasattr(ctypes, 'c_int64'):
                # Some builds of ctypes apparently do not have c_int64
                # defined; it's a pretty good bet that these builds do not
                # have 64-bit pointers.
                _int_types += (ctypes.c_int64,)
            for t in _int_types:
                if sizeof(t) == sizeof(c_size_t):
                    c_ptrdiff_t = t

            class c_void(Structure):
                # c_void_p is a buggy return type, converting to int, so
                # POINTER(None) == c_void_p is actually written as
                # POINTER(c_void), so it can be treated as a real pointer.
                _fields_ = [('dummy', c_int)]

            _libs = {}

            # As of ctypes 1.0, ctypes does not support custom error-checking
            # functions on callbacks, nor does it support custom datatypes on
            # callbacks, so we must ensure that all callbacks return
            # primitive datatypes.
            #
            # Non-primitive return values wrapped with UNCHECKED won't be
            # typechecked, and will be converted to c_void_p.
            def UNCHECKED(type):
                if (hasattr(type, "_type_") and isinstance(type._type_, str)
                    and type._type_ != "P"):
                    return type
                else:
                    return c_void_p
        """ % {
            'library': str(self.library),
            'date': time.ctime(),
            'class': self.__class__.__name__,
            'argv': ' '.join(sys.argv),
        }).lstrip()
        self.loaded_libraries = []
        for library in self.library:
            lib = load_library(library)
            if lib:
                self.loaded_libraries.append(lib)
                print >>self.file, textwrap.dedent("""
                    _libs[%r] = CDLL(%r, mode=RTLD_GLOBAL)
                """ % (lib._name, lib._name))

    def print_link_modules_imports(self):
        for name in self.link_modules:
            print >> self.file, 'from %s import *' % name
        print >> self.file

    def print_epilogue(self):
{'fraction_non_alphanumeric': 0.09156626506024096, 'fraction_numerical': 0.008897126969416125, 'mean_word_length': 1.8668969181721573, 'pattern_counts': {'":': 2, '<': 3, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7667698', 'n_tokens_mistral': 3239, 'n_tokens_neox': 3056, 'n_words': 865}