def __init__(self): if len(self.__dict__) > 0: return self.security = cdll.LoadLibrary( "/System/Library/Frameworks/Security.framework/Versions/Current/Security" ) def load_func(name, rtype, args): func = getattr(self.security, name) func.restype = rtype func.argtypes = args load_func("SecItemCopyMatching", c_int32, [c_void_p, POINTER(c_void_p)]) load_func("SecItemDelete", c_int32, [c_void_p]) load_func("SecKeyCreateSignature", c_void_p, [c_void_p, c_void_p, c_void_p, POINTER(c_void_p)]) load_func("SecKeyIsAlgorithmSupported", c_ubyte, [c_void_p, CFIndex, c_void_p]) load_func("SecAccessControlCreateWithFlags", c_void_p, [CFAllocatorRef, c_void_p, c_ulong, POINTER(c_void_p)]) load_func("SecKeyCreateRandomKey", c_void_p, [c_void_p, POINTER(c_void_p)]) load_func("SecKeyCopyPublicKey", c_void_p, [c_void_p]) load_func("SecKeyCopyExternalRepresentation", c_void_p, [c_void_p, POINTER(c_void_p)]) load_func("SecItemAdd", c_int32, [c_void_p, POINTER(c_void_p)]) load_func("SecItemUpdate", c_int32, [c_void_p, c_void_p]) load_func("SecAccessCreate", c_int32, [c_void_p, c_void_p, POINTER(c_void_p)]) load_func("SecACLCreateWithSimpleContents", c_int32, [c_void_p, c_void_p, c_void_p, c_uint16, POINTER(c_void_p)]) attr_list = [ "kSecClass", "kSecClassKey", "kSecAttrLabel", "kSecAttrKeyClass", "kSecAttrKeyClassPrivate", "kSecReturnRef", "kSecReturnAttributes", "kSecValueRef", "kSecAttrKeyType", "kSecAttrKeySizeInBits", "kSecValueRef", "kSecAttrKeyType", "kSecAttrKeySizeInBits", "kSecAttrKeyTypeRSA", "kSecAttrKeyTypeECSECPrimeRandom", "kSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA256", "kSecKeyAlgorithmECDSASignatureDigestX962SHA256", "kSecAttrTokenID", "kSecAttrTokenIDSecureEnclave", "kSecPrivateKeyAttrs", "kSecAttrIsPermanent", "kSecAttrAccessControl", "kSecAttrAccess", "kSecAttrAccessibleAfterFirstUnlock", "kSecAttrApplicationTag" ] for attr in attr_list: setattr(self, attr, c_void_p.in_dll(self.security, attr)) self.kSecAccessControlPrivateKeyUsage = 1 << 30 cf.CFRetain.restype = c_void_p cf.CFRetain.argtypes = [c_void_p] self.kCFBooleanTrue = c_void_p.in_dll(cf, "kCFBooleanTrue") self.errSecSuccess = 0 self.errSecItemNotFound = -25300
def _set_readline_display_matches(self): ''' In order to stay compatible with python versions < 2.6, we are not using readline.set_completion_display_matches_hook() but instead use ctypes there to bind to the C readline hook if needed. This hooks a callback function to display readline completions. ''' if 'set_completion_display_matches_hook' in dir(readline): readline.set_completion_display_matches_hook( self._display_completions_python) else: from ctypes import cdll, CFUNCTYPE, POINTER from ctypes import c_char_p, c_int, c_void_p, cast libreadline = None try: libreadline = cdll.LoadLibrary('libreadline.so') except OSError: try: libreadline = cdll.LoadLibrary('libreadline.so.5') except OSError: try: libreadline = cdll.LoadLibrary('libreadline.so.6') except OSError: self.log.critical( "Could not find readline shared library.") if libreadline: completion_func_type = \ CFUNCTYPE(None, POINTER(c_char_p), c_int, c_int) hook = completion_func_type(self._display_completions) ptr = c_void_p.in_dll(libreadline, 'rl_completion_display_matches_hook') ptr.value = cast(hook, c_void_p).value
def __init__(self): for mod, table in [(sc, sctable), (cf, cftable)]: for fname, argtypes, restype in table: func = getattr(mod, fname) func.argtypes = argtypes func.restype = restype setattr(self, fname, func) for k in scconst: v = None try: v = c_void_p.in_dll(sc, k) except ValueError: v = None setattr(self, k, v)
def _install_readline(): global _original assert _installed if _original is not None: logger.warning('readline hook already installed') return logger.info('installing readline hook') rfp = c_void_p.in_dll(pythonapi, 'PyOS_ReadlineFunctionPointer') _original = rfp.value if _original is None: logger.warning('could not install - will wait for _PathFinder') return _original = PyOS_ReadlineFunctionPointer_t(_original) rfp.value = cast(_call_readline, c_void_p).value
def setup_posix(libR): set_posix_cb_ptr(libR, "ptr_R_Suicide", "R_Suicide") set_posix_cb_ptr(libR, "ptr_R_ShowMessage", "R_ShowMessage") set_posix_cb_ptr(libR, "ptr_R_ReadConsole", "R_ReadConsole") set_posix_cb_ptr(libR, "ptr_R_WriteConsole", "R_WriteConsole") set_posix_cb_ptr(libR, "ptr_R_WriteConsoleEx", "R_WriteConsoleEx") set_posix_cb_ptr(libR, "ptr_R_ResetConsole", "R_ResetConsole") set_posix_cb_ptr(libR, "ptr_R_FlushConsole", "R_FlushConsole") set_posix_cb_ptr(libR, "ptr_R_ClearerrConsole", "R_ClearerrConsole") set_posix_cb_ptr(libR, "ptr_R_Busy", "R_Busy") if callback_dict["R_CleanUp"]: ptr_R_CleanUp = c_void_p.in_dll(libR, 'ptr_R_CleanUp') orig_cleanup = PYFUNCTYPE(None, c_int, c_int, c_int)(ptr_R_CleanUp.value) def _handler(save_type, status, runlast): callback_dict["R_CleanUp"](save_type, status, runlast) orig_cleanup(save_type, status, runlast) ptr_new_R_CleanUp = PYFUNCTYPE(None, c_int, c_int, c_int)(_handler) callback_pointer.append(ptr_new_R_CleanUp) ptr_R_CleanUp.value = cast(ptr_new_R_CleanUp, c_void_p).value set_posix_cb_ptr(libR, "ptr_R_ShowFiles", "R_ShowFiles") set_posix_cb_ptr(libR, "ptr_R_ChooseFile", "R_ChooseFile") set_posix_cb_ptr(libR, "ptr_R_EditFile", "R_EditFile") set_posix_cb_ptr(libR, "ptr_R_loadhistory", "R_loadhistory") set_posix_cb_ptr(libR, "ptr_R_savehistory", "R_savehistory") set_posix_cb_ptr(libR, "ptr_R_addhistory", "R_addhistory") set_posix_cb_ptr(libR, "ptr_R_EditFiles", "R_EditFiles") set_posix_cb_ptr(libR, "ptr_do_selectlist", "do_selectlist") set_posix_cb_ptr(libR, "ptr_do_dataentry", "do_dataentry") set_posix_cb_ptr(libR, "ptr_do_dataviewer", "do_dataviewer") set_posix_cb_ptr(libR, "ptr_R_ProcessEvents", "R_ProcessEvents") set_posix_cb_ptr(libR, "ptr_do_dataviewer", "do_dataviewer") set_posix_cb_ptr(libR, "R_PolledEvents", "R_PolledEvents")
CoreFoundation.CFArrayGetCount.argtypes = [ CFArrayRef ] CoreFoundation.CFArrayGetCount.restype = CFIndex CoreFoundation.CFArrayGetValueAtIndex.argtypes = [ CFArrayRef, CFIndex ] CoreFoundation.CFArrayGetValueAtIndex.restype = c_void_p CoreFoundation.kCFAllocatorDefault = CFAllocatorRef.in_dll( CoreFoundation, 'kCFAllocatorDefault' ) CoreFoundation.kCFTypeArrayCallBacks = c_void_p.in_dll(CoreFoundation, 'kCFTypeArrayCallBacks') CoreFoundation.kCFTypeDictionaryKeyCallBacks = c_void_p.in_dll( CoreFoundation, 'kCFTypeDictionaryKeyCallBacks' ) CoreFoundation.kCFTypeDictionaryValueCallBacks = c_void_p.in_dll( CoreFoundation, 'kCFTypeDictionaryValueCallBacks' ) CoreFoundation.CFTypeRef = CFTypeRef CoreFoundation.CFArrayRef = CFArrayRef CoreFoundation.CFStringRef = CFStringRef CoreFoundation.CFDictionaryRef = CFDictionaryRef except (AttributeError): raise ImportError('Error initializing ctypes')
NSAlertFirstButtonReturn = 1000 NSAlertSecondButtonReturn = 1001 NSAlertThirdButtonReturn = 1002 ###################################################################### # NSApplication.h NSApplication = ObjCClass('NSApplication') NSApplication.declare_class_property('sharedApplication') NSApplicationPresentationDefault = 0 NSApplicationPresentationHideDock = 1 << 1 NSApplicationPresentationHideMenuBar = 1 << 3 NSApplicationPresentationDisableProcessSwitching = 1 << 5 NSApplicationPresentationDisableHideApplication = 1 << 8 NSEventTrackingRunLoopMode = c_void_p.in_dll(appkit, 'NSEventTrackingRunLoopMode') NSApplicationDidHideNotification = c_void_p.in_dll( appkit, 'NSApplicationDidHideNotification') NSApplicationDidUnhideNotification = c_void_p.in_dll( appkit, 'NSApplicationDidUnhideNotification') NSAboutPanelOptionApplicationIcon = NSString( c_void_p.in_dll(appkit, "NSAboutPanelOptionApplicationIcon")) NSAboutPanelOptionApplicationName = NSString( c_void_p.in_dll(appkit, "NSAboutPanelOptionApplicationName")) NSAboutPanelOptionApplicationVersion = NSString( c_void_p.in_dll(appkit, "NSAboutPanelOptionApplicationVersion")) NSAboutPanelOptionCredits = NSString( c_void_p.in_dll(appkit, "NSAboutPanelOptionCredits")) NSAboutPanelOptionVersion = NSString(
NSAlertFirstButtonReturn = 1000 NSAlertSecondButtonReturn = 1001 NSAlertThirdButtonReturn = 1002 ###################################################################### # NSApplication.h NSApplication = ObjCClass('NSApplication') NSApplication.declare_class_property('sharedApplication') NSApplicationPresentationDefault = 0 NSApplicationPresentationHideDock = 1 << 1 NSApplicationPresentationHideMenuBar = 1 << 3 NSApplicationPresentationDisableProcessSwitching = 1 << 5 NSApplicationPresentationDisableHideApplication = 1 << 8 NSEventTrackingRunLoopMode = c_void_p.in_dll(appkit, 'NSEventTrackingRunLoopMode') NSApplicationDidHideNotification = c_void_p.in_dll( appkit, 'NSApplicationDidHideNotification') NSApplicationDidUnhideNotification = c_void_p.in_dll( appkit, 'NSApplicationDidUnhideNotification') ###################################################################### # NSAttributedString.h NSAttributedString = ObjCClass('NSAttributedString') NSFontAttributeName = objc_const(appkit, "NSFontAttributeName") NSParagraphStyleAttributeName = objc_const(appkit, "NSParagraphStyleAttributeName") NSForegroundColorAttributeName = objc_const(appkit, "NSForegroundColorAttributeName")
# UISlider.h UISlider = ObjCClass('UISlider') # UISwitch.h UISwitch = ObjCClass('UISwitch') # Attributed String stuff NSAttributedString = ObjCClass('NSAttributedString') NSMutableAttributedString = ObjCClass('NSMutableAttributedString') # Paragraph Style NSParagraphStyle = ObjCClass('NSParagraphStyle') NSMutableParagraphStyle = ObjCClass('NSMutableParagraphStyle') # Below Attributes come from NSAttributedString.h NSFontAttributeName = ObjCInstance( c_void_p.in_dll(uikit, 'NSFontAttributeName')) NSParagraphStyleAttributeName = ObjCInstance( c_void_p.in_dll(uikit, 'NSParagraphStyleAttributeName')) NSForegroundColorAttributeName = ObjCInstance( c_void_p.in_dll(uikit, 'NSForegroundColorAttributeName')) NSBackgroundColorAttributeName = ObjCInstance( c_void_p.in_dll(uikit, 'NSBackgroundColorAttributeName')) NSLigatureAttributeName = ObjCInstance( c_void_p.in_dll(uikit, 'NSLigatureAttributeName')) NSKernAttributeName = ObjCInstance( c_void_p.in_dll(uikit, 'NSKernAttributeName')) NSStrikethroughStyleAttributeName = ObjCInstance( c_void_p.in_dll(uikit, 'NSStrikethroughStyleAttributeName')) NSUnderlineStyleAttributeName = ObjCInstance( c_void_p.in_dll(uikit, 'NSUnderlineStyleAttributeName')) NSStrokeColorAttributeName = ObjCInstance(
sign_bit = 1 << (word_bit - 1) hex0x_word_width = word_bytes * 2 + 2 # Width of a hex word with leading "0x" uword_max = c_uword(-1).value # Functions from mit.h # Errors mit_error = errcheck(MitErrorCode) # Bind `mit_run` as a function and as a function pointer, because # for some reason we can't call it when bound as a pointer. _run = c_mit_fn.in_dll(libmit, "mit_run") run_ptr = POINTER(c_mit_fn).in_dll(libmit, "mit_run") # `break_fn_ptr` must be bound as a `c_void_p` in order to be set to point # to a Python callback. break_fn_ptr = c_void_p.in_dll(libmit, "mit_break_fn") stack_words_ptr = pointer(c_uword.in_dll(libmit, "mit_stack_words")) stack_words = c_uword.in_dll(libmit, "mit_stack_words") run_simple = c_mit_fn.in_dll(libmit, "mit_run_simple") run_break = c_mit_fn.in_dll(libmit, "mit_run_break") # run_fast = c_mit_fn.in_dll(libmit, "mit_run_fast") # run_profile = c_mit_fn.in_dll(libmit, "mit_run_profile") # Cannot add errcheck to a CFUNCTYPE, so wrap it manually. def run(pc, ir, stack, stack_words, stack_depth_ptr): return mit_error(_run(pc, ir, stack, stack_words, stack_depth_ptr)) # libmit.mit_profile_reset.restype = None
(2, lib.covar), (3, lib.reshape), (3, lib.apply), ] for arity, api in apis: api.argtypes = [c_void_p] * arity api.restype = c_void_p def version() -> str: """version binds version.""" return lib.version().decode() mul = c_void_p.in_dll(lib, 'op_mul') add = c_void_p.in_dll(lib, 'op_add') softmax = c_void_p.in_dll(lib, 'op_softmax') # pylint: disable=too-few-public-methods class Shape(object): """Shape is shape_t.""" def __init__(self, *dims: int): rank = len(dims) self.handle = lib.new_shape(rank, *dims) def __del__(self): lib.del_shape(self.handle)
sys.exit(-1) else: supp_platforms = ['Linux', 'Darwin'] print('Supported platforms: '), supp_platforms sys.exit(-1) try: libc = cdll.LoadLibrary(find_library('c')) except ImportError: import sys print('Error: unable to find libc') sys.exit(-1) if (platform.system() == 'Linux'): c_stdout = c_void_p.in_dll(libc, "stdout") elif (platform.system() == "Darwin"): c_stdout = c_void_p.in_dll(libc, '__stdoutp') else: supp_platforms = ['Linux', 'Darwin'] print('Supported platforms: '), supp_platforms sys.exit(-1) libblockmatching.API_blockmatching.restype = POINTER(BAL_TRSF) def return_value(values, rcode): if rcode == -1: return None # return result image
# https://gist.github.com/jsbain/99303488cf6af6d7ef8b9b43a46ca414 from datetime import datetime from objc_util import c, CGRect, nsurl,ns,ObjCInstance, ObjCClass,NSURL from quartz import quartz from ctypes import c_void_p, c_int, c_double, c_float, c_size_t,c_bool, c_char_p, sizeof import os if sizeof(c_size_t)==8: CFFloat=c_double else: CFFloat=c_float width = height = 1024 #this needs to be an integer, no decimal kCGColorSpaceSRGB=ObjCInstance(c_void_p.in_dll(quartz,'kCGColorSpaceSRGB')) kCGImageAlphaPremultipliedLast=1 kCGPathFillStroke=3 #these are needed because argtypes are not all voids quartz.CGImageDestinationCreateWithURL.argtypes=[c_void_p,c_void_p,c_int,c_void_p] quartz.CGContextSetRGBFillColor.argtypes=[c_void_p, CFFloat, CFFloat, CFFloat, CFFloat] quartz.CGColorSpaceCreateWithName.argtypes=[c_void_p] quartz.CFURLCreateFromFileSystemRepresentation.argtypes=[c_void_p,c_char_p,c_size_t,c_bool] #for some rewson this one fails. color_space = quartz.CGColorSpaceCreateWithName(kCGColorSpaceSRGB) if not color_space: color_space=quartz.CGColorSpaceCreateDeviceRGB() print('falling back to devicergb colorspace') ctx = quartz.CGBitmapContextCreate(None, width, height, 8, width * 4, color_space, kCGImageAlphaPremultipliedLast) if not ctx:
return cdll[path] LIBC = get_libc() PyMem_Malloc = pythonapi.PyMem_Malloc PyMem_Malloc.restype = c_size_t PyMem_Malloc.argtypes = [c_size_t] strncpy = LIBC.strncpy strncpy.restype = c_char_p strncpy.argtypes = [c_char_p, c_char_p, c_size_t] HOOKFUNC = CFUNCTYPE(c_char_p, c_void_p, c_void_p, c_char_p) PyOS_ReadlineFunctionPointer = c_void_p.in_dll(pythonapi, "PyOS_ReadlineFunctionPointer") def new_zero_terminated_string(b): p = PyMem_Malloc(len(b) + 1) strncpy(cast(p, c_char_p), b, len(b) + 1) return p def check_encodings(): if sys.stdin.encoding != sys.stdout.encoding: # raise RuntimeError("sys.stdin.encoding != sys.stdout.encoding, readline hook doesn't know, which one to use to decode prompt") warnings.warn("sys.stdin.encoding == {!r}, whereas sys.stdout.encoding == {!r}, readline hook consumer may assume they are the same".format(sys.stdin.encoding, sys.stdout.encoding), RuntimeWarning, stacklevel=3) def stdio_readline(prompt=""):
# CFRunLoopRef CFRunLoopGetCurrent() CFRunLoopGetCurrent = CoreFoundation.CFRunLoopGetCurrent CFRunLoopGetCurrent.restype = c_void_p CFRunLoopGetCurrent.argtypes = [] # void CFRelease(CFTypeRef) CFRelease = CoreFoundation.CFRelease CFRelease.restype = None CFRelease.argtypes = [c_void_p] # void CFRunLoopRun() CFRunLoopRun = CoreFoundation.CFRunLoopRun # const CFStringRef kCFRunLoopDefaultMode # pylint: disable=E1101 kCFRunLoopDefaultMode = c_void_p.in_dll(CoreFoundation, "kCFRunLoopDefaultMode") # Functions and constants below are from # /System/Library/SystemConfiguration.framework/ SystemConfigurationPath = find_library("SystemConfiguration") # SystemConfiguration abbreviated as "SC" below: SC = CDLL(SystemConfigurationPath) # "SCNetworkReachability" functions abbreviated to "SCNR*" here. # SCNetworkReachabilityRef # SCNetworkReachabilityCreateWithName(CFAllocatorRef, const char *) SCNRCreateWithName = SC.SCNetworkReachabilityCreateWithName SCNRCreateWithName.restype = c_void_p
def set_func_ptr(lib: CDLL, name: str, func_ptr): try: c_void_p.in_dll(lib, name).value = cast(func_ptr, c_void_p).value except Exception as e: log.w(f"set_func_ptr failed: {e}") raise CException(e)
CFAllocatorRef, CFIndex, CFArrayCallBacks ] CoreFoundation.CFArrayCreateMutable.restype = CFMutableArrayRef CoreFoundation.CFArrayAppendValue.argtypes = [CFMutableArrayRef, c_void_p] CoreFoundation.CFArrayAppendValue.restype = None CoreFoundation.CFArrayGetCount.argtypes = [CFArrayRef] CoreFoundation.CFArrayGetCount.restype = CFIndex CoreFoundation.CFArrayGetValueAtIndex.argtypes = [CFArrayRef, CFIndex] CoreFoundation.CFArrayGetValueAtIndex.restype = c_void_p CoreFoundation.kCFAllocatorDefault = CFAllocatorRef.in_dll( CoreFoundation, 'kCFAllocatorDefault') CoreFoundation.kCFTypeArrayCallBacks = c_void_p.in_dll( CoreFoundation, 'kCFTypeArrayCallBacks') CoreFoundation.kCFTypeDictionaryKeyCallBacks = c_void_p.in_dll( CoreFoundation, 'kCFTypeDictionaryKeyCallBacks') CoreFoundation.kCFTypeDictionaryValueCallBacks = c_void_p.in_dll( CoreFoundation, 'kCFTypeDictionaryValueCallBacks') CoreFoundation.CFTypeRef = CFTypeRef CoreFoundation.CFArrayRef = CFArrayRef CoreFoundation.CFStringRef = CFStringRef CoreFoundation.CFDictionaryRef = CFDictionaryRef except (AttributeError): raise ImportError('Error initializing ctypes') class CFConst(object):
from ctypes import c_void_p import ctypes.util libc_path = ctypes.util.find_library('c') print libc_path libc = ctypes.cdll.LoadLibrary(libc_path) print libc for name in ( 'stdout', # glibc '__stdoutp', # darwin ): try: stdout = c_void_p.in_dll(libc, name) except ValueError: continue else: break print stdout
def k_(s): return c_void_p.in_dll(_sec, s)
('send_event', c_int), ('display', c_void_p), ('requestor', c_ulong), ('selection', c_ulong), ('target', c_ulong), ('property', c_ulong), ('time', c_ulong)] class XEvent(Union): """X11 XEvent union""" _fields_ = [('type', c_int), ('xselection', XSelectionEvent), ('pad', c_long*24)] PRIMARY, SECONDARY = 1, 2 CLIPBOARD = c_void_p.in_dll(Xmu, '_XA_CLIPBOARD') _XA_UTF8_STRING = c_void_p.in_dll(Xmu, '_XA_UTF8_STRING') def get(selection=PRIMARY): """Get the value of a selection of X11""" display = X11.XOpenDisplay(None) if not display: raise RuntimeError("XOpenDisplay did not succeed") try: window = X11.XDefaultRootWindow(display) window = X11.XCreateSimpleWindow(display, window, 0, 0, 1, 1, 0, 0, 0) if isinstance(selection, c_void_p): selection = Xmu.XmuInternAtom(display, selection) prop = X11.XInternAtom(display, 'pyXsel', False)
core_text.CTFontCopyFullName.restype = c_void_p core_text.CTFontCopyFullName.argtypes = [c_void_p] core_text.CTFontCreateWithFontDescriptor.restype = c_void_p core_text.CTFontCreateWithFontDescriptor.argtypes = [ c_void_p, CGFloat, c_void_p ] core_text.CTFontDescriptorCreateWithAttributes.restype = c_void_p core_text.CTFontDescriptorCreateWithAttributes.argtypes = [c_void_p] ###################################################################### # CTFontDescriptor.h kCTFontFamilyNameAttribute = c_void_p.in_dll(core_text, 'kCTFontFamilyNameAttribute') kCTFontTraitsAttribute = c_void_p.in_dll(core_text, 'kCTFontTraitsAttribute') ###################################################################### # CTFontTraits.h kCTFontSymbolicTrait = c_void_p.in_dll(core_text, 'kCTFontSymbolicTrait') kCTFontWeightTrait = c_void_p.in_dll(core_text, 'kCTFontWeightTrait') kCTFontItalicTrait = (1 << 0) kCTFontBoldTrait = (1 << 1) ###################################################################### # CTLine.h core_text.CTLineCreateWithAttributedString.restype = c_void_p
def get_particle_filter(self): return c_void_p.in_dll(self.libmicrocontroller, 'pfPointer')
if method.it: return GENERAL_NAMES( _ASN1_item_d2i(None, byref(data_in), asn1_octet_string.length, _ASN1_ITEM_ptr(method.it))) func_ptr = _rvoidp_voidp_ubytepp_long(method.d2i) return GENERAL_NAMES( func_ptr(None, byref(data_in), asn1_octet_string.length)) def sk_value(stack, loc): return cast(_sk_value(stack, loc), POINTER(stack.stack_element_type)) def GENERAL_NAME_print(general_name): bio = _BIO(BIO_new(BIO_s_mem())) _GENERAL_NAME_print(bio.value, general_name) return BIO_gets(bio.value) _free_func = addressof(c_void_p.in_dll(libcrypto, "sk_free")) def sk_pop_free(stack): _sk_pop_free(stack, _free_func) def i2d_X509(x509): bio = _BIO(BIO_new(BIO_s_mem())) _i2d_X509_bio(bio.value, x509) return BIO_get_mem_data(bio.value)
def get_triliteration_data(self): return c_void_p.in_dll(self.libmicrocontroller, 'dataPointer')
def set_posix_cb_ptr(libR, ptrname, name): if callback_dict[name]: cb_ptr = get_cb_ptr(name) # prevent gc callback_pointer.append(cb_ptr) c_void_p.in_dll(libR, ptrname).value = cast(cb_ptr, c_void_p).value
def _unwrap_exception(self, jl_exc): exception = void_p.in_dll(self.api, 'jl_exception_in_transit') msg = self.api.jl_typeof_str(exception) return char_p(msg).value
def _typeof_julia_exception_in_transit(self): exception = void_p.in_dll(self.api, 'jl_exception_in_transit') msg = self.api.jl_typeof_str(exception) return char_p(msg).value
_rvoidp_voidp_ubytepp_long = CFUNCTYPE(c_void_p, c_void_p, POINTER(POINTER(c_ubyte)), c_long) def ASN1_item_d2i(method, asn1_octet_string): data_in = POINTER(c_ubyte)(asn1_octet_string.data.contents) if method.it: return GENERAL_NAMES(_ASN1_item_d2i(None, byref(data_in), asn1_octet_string.length, _ASN1_ITEM_ptr(method.it))) func_ptr = _rvoidp_voidp_ubytepp_long(method.d2i) return GENERAL_NAMES(func_ptr(None, byref(data_in), asn1_octet_string.length)) def sk_value(stack, loc): return cast(_sk_value(stack, loc), POINTER(stack.stack_element_type)) def GENERAL_NAME_print(general_name): bio = _BIO(BIO_new(BIO_s_mem())) _GENERAL_NAME_print(bio.value, general_name) return BIO_gets(bio.value) _free_func = addressof(c_void_p.in_dll(libcrypto, "sk_free")) def sk_pop_free(stack): _sk_pop_free(stack, _free_func) def i2d_X509(x509): bio = _BIO(BIO_new(BIO_s_mem())) _i2d_X509_bio(bio.value, x509) return BIO_get_mem_data(bio.value)
def _str_symbol(name): return ObjCInstance(c_void_p.in_dll(c, name))
import sys, traceback from ctypes import pythonapi, cdll, c_size_t, c_char_p, c_void_p, cast, CFUNCTYPE, POINTER, addressof PyMem_Malloc = pythonapi.PyMem_Malloc PyMem_Malloc.restype = c_size_t PyMem_Malloc.argtypes = [c_size_t] strncpy = cdll.msvcrt.strncpy strncpy.restype = c_char_p strncpy.argtypes = [c_char_p, c_char_p, c_size_t] HOOKFUNC = CFUNCTYPE(c_char_p, c_void_p, c_void_p, c_char_p) PyOS_ReadlineFunctionPointer = c_void_p.in_dll(pythonapi, "PyOS_ReadlineFunctionPointer") def new_zero_terminated_string(b): p = PyMem_Malloc(len(b) + 1) strncpy(cast(p, c_char_p), b, len(b) + 1) return p class ReadlineHookManager: def __init__(self): self.readline_wrapper_ref = HOOKFUNC(self.readline_wrapper) self.address = c_void_p.from_address( addressof(self.readline_wrapper_ref)).value self.original_address = PyOS_ReadlineFunctionPointer.value self.readline_hook = None
def setup_callbacks_posix(self): # ptr_R_Suicide if self.show_message: self.ptr_show_message = CFUNCTYPE(None, c_char_p)(self.show_message) ptr = c_void_p.in_dll(self.libR, 'ptr_R_ShowMessage') ptr.value = cast(self.ptr_show_message, c_void_p).value if self.read_console: # make sure it is not gc'ed self.ptr_read_console = \ CFUNCTYPE(c_int, c_char_p, POINTER(c_char), c_int, c_int)(self.read_console) ptr = c_void_p.in_dll(self.libR, 'ptr_R_ReadConsole') ptr.value = cast(self.ptr_read_console, c_void_p).value if self.write_console_ex: c_void_p.in_dll(self.libR, 'ptr_R_WriteConsole').value = None # make sure it is not gc'ed self.ptr_write_console_ex = \ CFUNCTYPE(None, c_char_p, c_int, c_int)(self.write_console_ex) ptr = c_void_p.in_dll(self.libR, 'ptr_R_WriteConsoleEx') ptr.value = cast(self.ptr_write_console_ex, c_void_p).value # ptr_R_ResetConsole # ptr_R_FlushConsole # ptr_R_ClearerrConsole if self.r_busy: self.ptr_r_busy = CFUNCTYPE(None, c_int)(self.r_busy) ptr = c_void_p.in_dll(self.libR, 'ptr_R_Busy') ptr.value = cast(self.ptr_r_busy, c_void_p).value if self.clean_up: ptr = c_void_p.in_dll(self.libR, 'ptr_R_CleanUp') R_CleanUp = ctypes.PYFUNCTYPE(None, c_int, c_int, c_int)(ptr.value) def _handler(save_type, status, runlast): self.clean_up(save_type, status, runlast) R_CleanUp(save_type, status, runlast) self.ptr_r_clean_up = ctypes.PYFUNCTYPE(None, c_int, c_int, c_int)(_handler) ptr.value = cast(self.ptr_r_clean_up, c_void_p).value # ptr_R_ShowFiles # ptr_R_ChooseFile # ptr_R_EditFile # ptr_R_loadhistory # ptr_R_savehistory # ptr_R_addhistory # ptr_R_EditFiles # ptr_do_selectlist # ptr_do_dataentry # ptr_do_dataviewer if self.process_event: self.ptr_process_event = CFUNCTYPE(None)(self.process_event) ptr = c_void_p.in_dll(self.libR, 'ptr_R_ProcessEvents') ptr.value = cast(self.ptr_process_event, c_void_p).value if self.polled_events: self.ptr_polled_events = CFUNCTYPE(None)(self.polled_events) ptr = c_void_p.in_dll(self.libR, 'R_PolledEvents') ptr.value = cast(self.ptr_polled_events, c_void_p).value
except KeyboardInterrupt: print(" See KeyboardInterrupt from darwin hook") if callable(ON_INTERRUPT): ON_INTERRUPT() return 0 if sys.platform == 'darwin': # On OSX, evtloop.Pending() always returns True, regardless of there being # any events pending. As such we can't use implementations 1 or 3 of the # inputhook as those depend on a pending/dispatch loop. inputhook_wx = inputhook_darwin capture_CtrlC() cback = CFUNCTYPE(c_int)(inputhook_wx) py_inphook = c_void_p.in_dll(pythonapi, 'PyOS_InputHook') py_inphook.value = cast(cback, c_void_p).value # import for Darwin! allow_idle() def ping(timeout=0.001): "ping wx" try: t0 = clock() app = wx.GetApp() if app is not None: assert is_wxMain() # Make a temporary event loop and process system events until # there are no more waiting, then allow idle events (which
if callable(ON_INTERRUPT): ON_INTERRUPT() return 0 if sys.platform == 'darwin': # On OSX, evtloop.Pending() always returns True, regardless of there being # any events pending. As such we can't use implementations 1 or 3 of the # inputhook as those depend on a pending/dispatch loop. inputhook_wx = inputhook_darwin try: capture_CtrlC() except: pass cback = CFUNCTYPE(c_int)(inputhook_wx) py_inphook = c_void_p.in_dll(pythonapi, 'PyOS_InputHook') py_inphook.value = cast(cback, c_void_p).value # import for Darwin! allow_idle() def ping(timeout=0.001): "ping wx" try: t0 = clock() app = wx.GetApp() if app is not None: assert is_wxMain() # Make a temporary event loop and process system events until # there are no more waiting, then allow idle events (which # will also deal with pending or posted wx events.)
def register_py_func(c_name, py_func, ret_type, *arg_types): idris_func = to_idris_func(py_func, ret_type, *arg_types) idris_funcs.append(idris_func) c_void_p.in_dll(cdll, c_name).value = cast(idris_func, c_void_p).value