def test_byref_pointer(self):
     from ctypes import c_short, c_uint, c_int, c_long, pointer, POINTER, byref
     LPINT = POINTER(c_int)
     LPINT.from_param(byref(c_int(42)))
     self.assertRaises(TypeError, LPINT.from_param, byref(c_short(22)))
     if c_int != c_long:
         self.assertRaises(TypeError, LPINT.from_param, byref(c_long(22)))
     self.assertRaises(TypeError, LPINT.from_param, byref(c_uint(22)))
 def test_array_pointers(self):
     from ctypes import c_short, c_uint, c_int, c_long, POINTER
     INTARRAY = c_int * 3
     ia = INTARRAY()
     self.assertEqual(len(ia), 3)
     self.assertEqual([ ia[i] for i in range(3) ], [0, 0, 0])
     LPINT = POINTER(c_int)
     LPINT.from_param((c_int * 3)())
     self.assertRaises(TypeError, LPINT.from_param, c_short * 3)
     self.assertRaises(TypeError, LPINT.from_param, c_long * 3)
     self.assertRaises(TypeError, LPINT.from_param, c_uint * 3)
Example #3
0
    def test_pointer_subclasses(self):
        from ctypes import POINTER, c_void_p

        Void_pp = POINTER(c_void_p)
        class My_void_p(c_void_p):
            pass

        My_void_pp = POINTER(My_void_p)
        o = My_void_pp()

        assert Void_pp.from_param(o) is o
Example #4
0
    def test_byref_pointerpointer(self):
        # See above
        from ctypes import c_short, c_uint, c_int, c_long, pointer, POINTER, byref

        LPLPINT = POINTER(POINTER(c_int))
        LPLPINT.from_param(byref(pointer(c_int(42))))

        raises(TypeError, LPLPINT.from_param, byref(pointer(c_short(22))))
        if c_int != c_long:
            raises(TypeError, LPLPINT.from_param, byref(pointer(c_long(22))))
        raises(TypeError, LPLPINT.from_param, byref(pointer(c_uint(22))))
 def test_int_pointers(self):
     from ctypes import c_short, c_uint, c_int, c_long, POINTER, pointer
     LPINT = POINTER(c_int)
     x = LPINT.from_param(pointer(c_int(42)))
     self.assertEqual(x.contents.value, 42)
     self.assertEqual(LPINT(c_int(42)).contents.value, 42)
     self.assertEqual(LPINT.from_param(None), None)
     if c_int != c_long:
         self.assertRaises(TypeError, LPINT.from_param, pointer(c_long(42)))
     self.assertRaises(TypeError, LPINT.from_param, pointer(c_uint(42)))
     self.assertRaises(TypeError, LPINT.from_param, pointer(c_short(42)))
     return
Example #6
0
    def test_byref_pointer(self):
        # The from_param class method of POINTER(typ) classes accepts what is
        # returned by byref(obj), it type(obj) == typ
        from ctypes import c_short, c_uint, c_int, c_long, pointer, POINTER, byref
        LPINT = POINTER(c_int)

        LPINT.from_param(byref(c_int(42)))

        self.assertRaises(TypeError, LPINT.from_param, byref(c_short(22)))
        if c_int != c_long:
            self.assertRaises(TypeError, LPINT.from_param, byref(c_long(22)))
        self.assertRaises(TypeError, LPINT.from_param, byref(c_uint(22)))
Example #7
0
    def test_array_pointers(self):
        from ctypes import c_short, c_uint, c_int, c_long, POINTER
        INTARRAY = c_int * 3
        ia = INTARRAY()
        self.assertEqual(len(ia), 3)
        self.assertEqual([ia[i] for i in range(3)], [0, 0, 0])

        # Pointers are only compatible with arrays containing items of
        # the same type!
        LPINT = POINTER(c_int)
        LPINT.from_param((c_int*3)())
        self.assertRaises(TypeError, LPINT.from_param, c_short*3)
        self.assertRaises(TypeError, LPINT.from_param, c_long*3)
        self.assertRaises(TypeError, LPINT.from_param, c_uint*3)
Example #8
0
    def test_int_pointers(self):
        from ctypes import c_short, c_uint, c_int, c_long, POINTER, pointer
        LPINT = POINTER(c_int)

##        p = pointer(c_int(42))
##        x = LPINT.from_param(p)
        x = LPINT.from_param(pointer(c_int(42)))
        assert x.contents.value == 42
        assert LPINT(c_int(42)).contents.value == 42

        assert not LPINT.from_param(None)

        if c_int != c_long:
            raises(TypeError, LPINT.from_param, pointer(c_long(42)))
        raises(TypeError, LPINT.from_param, pointer(c_uint(42)))
        raises(TypeError, LPINT.from_param, pointer(c_short(42)))
Example #9
0
    def test_int_pointers(self):
        from ctypes import c_short, c_uint, c_int, c_long, POINTER, pointer
        LPINT = POINTER(c_int)

##        p = pointer(c_int(42))
##        x = LPINT.from_param(p)
        x = LPINT.from_param(pointer(c_int(42)))
        self.assertEqual(x.contents.value, 42)
        self.assertEqual(LPINT(c_int(42)).contents.value, 42)

        if not due_to_ironpython_bug("http://www.codeplex.com/IronPython/WorkItem/View.aspx?WorkItemId=24755"):
            self.assertEqual(LPINT.from_param(None), None)

        if c_int != c_long:
            self.assertRaises(TypeError, LPINT.from_param, pointer(c_long(42)))
        self.assertRaises(TypeError, LPINT.from_param, pointer(c_uint(42)))
        self.assertRaises(TypeError, LPINT.from_param, pointer(c_short(42)))
Example #10
0
 def __debug_create(self):
     """create IDebugClient"""
     
     self.__idebug_client = POINTER(DbgEng.IDebugClient)()
     hr = DebugCreate(byref(DbgEng.IDebugClient._iid_), byref(self.__idebug_client))
     if S_OK != hr:
         raise Exception('DebugCreate() fail.')
     else:
         logger.debug('[D] DebugClient: ' + str(self.__idebug_client))
Example #11
0
class cache(Structure):  # 192 bytes
    _fields_ = [("size", c_uint32), ("max_size", c_uint32),
                ("head", POINTER(cache_entry)), ("tail", POINTER(cache_entry)),
                ("map", POINTER(POINTER(cache_entry_map)))]
Example #12
0
 def _allocate_array(self, shape, c_type):
     assert len(shape) == 2
     insides = [(c_type * shape[1])() for i in range(shape[0])]
     out = (POINTER(c_type) * shape[0])(*insides)
     return out
Example #13
0
    def __getitem__(self, key):
        if self.verbose: print("*****")
        clibreboundx.rebx_get_param_node.restype = POINTER(Param)
        node = clibreboundx.rebx_get_param_node(byref(self.parent),
                                                c_char_p(key.encode('ascii')))

        if node:
            if self.verbose: print("Parameter {0} found".format(key))
            param = node.contents
            try:
                pythontype = self.ptype[param.python_type]
            except KeyError:
                pythontype = self.defaultptype[
                    param.param_type]  # Parameter was set in C, use default

            dtype, ctype, rebxtype = self.types[pythontype]
            if self.verbose:
                print("param.python_type= {0}, pythontype = {1}".format(
                    param.python_type, pythontype))
                print("dtype = {0}, ctype = {1}, rebxtype = {2}".format(
                    dtype, ctype, rebxtype))

            if param.ndim == 0:
                if self.verbose: print("Scalar")
                data = cast(param.contents, POINTER(ctype))
                try:
                    retval = data.contents.value  # cases where scalar is a ctype, so we get python type back
                    retval = pythontype(retval)
                except AttributeError:
                    if self.verbose: print("Parameter is a Structure")
                    retval = data.contents  # cases where scalar is a Structure, e.g., rebound.Orbit
            else:
                if self.verbose:
                    print("Parameter is an Array. ndim = {0}".format(
                        param.ndim))
                if self.verbose: print("Size = {0}".format(param.size))
                ArrayType = ctype * param.size
                data = cast(param.contents, POINTER(ArrayType))
                if dtype == object:  # can't use frombuffer with objects.
                    try:
                        array = np.array([
                            pythontype(data.contents[i])
                            for i in range(param.size)
                        ],
                                         dtype=dtype)
                    except TypeError:  # for cases where a custom ctypes Structure can't take a class instance in __init__
                        array = np.array(
                            [data.contents[i] for i in range(param.size)],
                            dtype=dtype)
                    #Makes copies of the ctypes.Structure instances, but fields share memory with C.
                else:
                    array = np.frombuffer(data.contents,
                                          dtype=dtype,
                                          count=param.size)
                if param.ndim > 1:
                    shape = [param.shape[i] for i in range(param.ndim)]
                    array = np.reshape(array, shape)
                    if self.verbose: print("Array shape = {0}".format(shape))
                retval = array
        else:
            raise AttributeError(
                "REBOUNDx Error: Parameter '{0}' not found.".format(key))

        if self.verbose: print("*****")
        return retval
od_path = find_library('OpenDirectory')
OpenDirectory = ctypes.CDLL(od_path, use_errno=True)

ODAttributeType = CoreFoundation.CFStringRef
ODMatchType = c_uint32
ODRecordType = CoreFoundation.CFStringRef

ODSessionRef = c_void_p
ODNodeRef = c_void_p
ODQueryRef = c_void_p
ODRecordRef = c_void_p

OpenDirectory.ODSessionCreate.argtypes = [
    CoreFoundation.CFAllocatorRef, CoreFoundation.CFDictionaryRef,
    POINTER(CoreFoundation.CFErrorRef)
]
OpenDirectory.ODSessionCreate.restype = ODSessionRef

OpenDirectory.ODNodeCreateWithName.argtypes = [
    CoreFoundation.CFAllocatorRef, ODSessionRef, CoreFoundation.CFStringRef,
    POINTER(CoreFoundation.CFErrorRef)
]
OpenDirectory.ODNodeCreateWithName.restype = ODNodeRef

OpenDirectory.ODQueryCreateWithNode.argtypes = [
    CoreFoundation.CFAllocatorRef, ODNodeRef, CoreFoundation.CFTypeRef,
    ODAttributeType, ODMatchType, CoreFoundation.CFTypeRef,
    CoreFoundation.CFTypeRef, CoreFoundation.CFIndex,
    POINTER(CoreFoundation.CFErrorRef)
]
Example #15
0
class DebugClient:
    """IDebugClient Wrapper"""
    
    def __init__(self):
        """DebugClient initialization"""

        self.__debug_create()


    def __debug_create(self):
        """create IDebugClient"""
        
        self.__idebug_client = POINTER(DbgEng.IDebugClient)()
        hr = DebugCreate(byref(DbgEng.IDebugClient._iid_), byref(self.__idebug_client))
        if S_OK != hr:
            raise Exception('DebugCreate() fail.')
        else:
            logger.debug('[D] DebugClient: ' + str(self.__idebug_client))

    def query_interface(self, interface):
        """IDebugClient::QueryInterface method"""

        return self.__idebug_client.QueryInterface(interface)


    def get_indentity(self):
        """IDebugClient::GetIdentity method"""

        buffer_size = 0x100
        identity_size = c_ulong(0)
        hr = self.__idebug_client._IDebugClient__com_GetIdentity(None, buffer_size, byref(identity_size))
        if S_OK != hr:
            raise Exception('GetIdentity() fail.')

        buffer_size = identity_size.value + 1
        buffer = create_string_buffer(buffer_size)
        hr = self.__idebug_client._IDebugClient__com_GetIdentity(buffer, buffer_size, byref(identity_size))
        if S_OK != hr:
            raise Exception('GetIdentity() fail.')
        
        return buffer.value

    def set_event_callbacks(self, event_callbacks):
        """IDebugClient::SetEventCallbacks method"""

        hr = self.__idebug_client.SetEventCallbacks(event_callbacks)
        if S_OK != hr:
            raise Exception('SetEventCallbacks() fail.')

    def get_event_callbacks(self):
        """IDebugClient::GetEventCallbacks method"""

        return self.__idebug_client.GetEventCallbacks()

    def set_output_callbacks(self, output_callbacks):
        """IDebugClient::SetOutputCallbacks method"""

        hr = self.__idebug_client.SetOutputCallbacks(output_callbacks)
        if S_OK != hr:
            raise Exception('SetOutputCallbacks() fail.')

    def get_output_callbacks(self):
        """IDebugClient::GetOutputCallbacks method"""

        return self.__idebug_client.GetOutputCallbacks()

    def get_running_process_ids(self):
        """IDebugClient::GetRunningProcessSystemIds method"""

        server = 0
        count = 256
        ids = (c_ulong * count)()
        actual_count = c_ulong(0)
        hr = self.__idebug_client._IDebugClient__com_GetRunningProcessSystemIds(server, ids, count, byref(actual_count))
        if S_OK != hr:
            raise Exception('GetRunningProcessSystemIds() fail.')

        return ids, actual_count.value

    def get_running_process_desc(self, sysid):
        """IDebugClient::GetRunningProcessDescription method"""

        try:
            server = 0
            flags  = DbgEng.DEBUG_PROC_DESC_NO_PATHS
            exename_size = 0x100
            exename = create_string_buffer(exename_size)
            actual_exename_size = c_ulong(0)
            description_size = 0x100
            description = create_string_buffer(description_size)
            actual_description_size = c_ulong(0)
                
            hr = self.__idebug_client._IDebugClient__com_GetRunningProcessDescription(
                server, sysid, flags,
                exename, exename_size, byref(actual_exename_size),
                description, description_size, byref(actual_description_size))
                
            if S_OK != hr:
                if S_FALSE == hr:
                    exename_size = actual_exename_size.value + 1
                    exename = create_string_buffer(exename_size)
                    description_size = actual_description_size.value + 1
                    description = create_string_buffer(description_size)
                        
                    hr = self.__idebug_client._IDebugClient__com_GetRunningProcessDescription(
                        server, sysid, flags,
                        exename, exename_size, byref(actual_exename_size),
                        description, description_size, byref(actual_description_size))
                    if S_OK != hr:
                        raise Exception('GetRunningProcessDescription() fail.')
                else:
                    raise Exception('GetRunningProcessDescription() fail.')
                    
        except COMError, msg:
            print 'No enough privilege to retrieve process information.'

        return exename.value, description.value
Example #16
0
class CallBack():
    def __init__(self, miniblink, width=360, height=480):
        self.mb = miniblink
        self.width = width
        self.height = height

    def wkeOnCreateView(self, webview, param=0):
        param = self.param_to_string(param)
        self.mb.wkeOnCreateView(webview, self._wkeCreateViewCallback,
                                _LRESULT(param))

    def wkeOnWindowClosing(self, webview, param=0):
        param = self.param_to_string(param)
        self.mb.wkeOnWindowClosing(webview, self._wkeWindowClosingCallback,
                                   _LRESULT(param))

    def wkeOnWindowDestroy(self, webview, param=0):

        self.mb.wkeOnWindowDestroy(webview, self._wkeWindowDestroyCallback,
                                   _LRESULT(param))

    def wkeOnPaintUpdated(self, webview, param=0):
        param = self.param_to_string(param)
        self.mb.wkeOnPaintUpdated(webview, self._wkePaintUpdatedCallback,
                                  _LRESULT(param))

    def wkeOnPaintBitUpdated(self, webview, param=0):
        param = self.param_to_string(param)
        self.mb.wkeOnPaintBitUpdated(webview, self._wkePaintBitUpdatedCallback,
                                     _LRESULT(param))

    def wkeOnNavigation(self, webview, param=0):
        param = self.param_to_string(param)
        self.mb.wkeOnNavigation(webview, self._wkeNavigationCallback,
                                _LRESULT(param))

    def wkeOnTitleChanged(self, webview, param=0):
        param = self.param_to_string(param)
        self.mb.wkeOnTitleChanged(webview, self._wkeTitleChangedCallback,
                                  _LRESULT(param))

    def wkeOnURLChanged2(self, webview, param=0):
        param = self.param_to_string(param)
        self.mb.wkeOnURLChanged2(webview, self._wkeURLChangedCallback2,
                                 _LRESULT(param))

    def wkeOnMouseOverUrlChanged(self, webview, param=0):
        param = self.param_to_string(param)
        self.mb.wkeOnMouseOverUrlChanged(webview,
                                         self._wkeMouseOverUrlChangedCallback,
                                         _LRESULT(param))

    def wkeOnAlertBox(self, webview, param=0):
        param = self.param_to_string(param)
        self.mb.wkeOnAlertBox(webview, self._wkeAlertBoxCallback,
                              _LRESULT(param))

    def wkeOnConfirmBox(self, webview, param=0):
        param = self.param_to_string(param)
        self.mb.wkeOnConfirmBox(webview, self._wkeConfirmBoxCallback,
                                _LRESULT(param))

    def wkeOnPromptBox(self, webview, param=0):
        param = self.param_to_string(param)
        self.mb.wkeOnPromptBox(webview, self._wkePromptBoxCallback,
                               _LRESULT(param))

    def wkeOnConsole(self, webview, param=0):
        self.mb.wkeOnConsole(webview, self._wkeConsoleCallback,
                             _LRESULT(param))

    def wkeOnDownload(self, webview, param=0):
        param = self.param_to_string(param)
        self.mb.wkeOnDownload(webview, self._wkeDownloadCallback,
                              _LRESULT(param))

    def wkeOnDocumentReady2(self, webview, param=0):
        param = self.param_to_string(param)
        self.mb.wkeOnDocumentReady2(webview, self._wkeDocumentReady2Callback,
                                    _LRESULT(param))

    def wkeNetOnResponse(self, webview, param=0):
        param = self.param_to_string(param)
        self.mb.wkeNetOnResponse(webview, self._wkeNetResponseCallback,
                                 _LRESULT(param))

    def wkeOnLoadUrlBegin(self, webview, param=0):
        param = self.param_to_string(param)
        self.mb.wkeOnLoadUrlBegin(webview, self._wkeLoadUrlBeginCallback,
                                  _LRESULT(param))

    def wkeOnLoadUrlEnd(self, webview, param=0):
        param = self.param_to_string(param)
        self.mb.wkeOnLoadUrlEnd(webview, self._wkeLoadUrlEndCallback,
                                _LRESULT(param))

    def wkeOnLoadUrlFail(self, webview, param=0):
        param = self.param_to_string(param)
        self.mb.wkeOnLoadUrlFail(webview, self._wkeLoadUrlFailCallback,
                                 _LRESULT(param))

    def wkeOnLoadingFinish(self, webview, param=0):
        param = self.param_to_string(param)
        self.mb.wkeOnLoadingFinish(webview, self._wkeLoadingFinishCallback,
                                   _LRESULT(param))

    def wkeNetGetFavicon(self, webview, param=0):
        param = self.param_to_string(param)
        self.mb.wkeNetGetFavicon(webview, self._wkeOnNetGetFaviconCallback,
                                 _LRESULT(param))

    @method(CFUNCTYPE(c_bool, _LRESULT, c_void_p))
    def _wkeWindowClosingCallback(self, webview, param):

        if hasattr(self, 'wkeWindowClosingCallback'):
            param = self.get_param_value(param)
            return self.wkeWindowClosingCallback(webview=webview, param=param)
        return True

    @method(CFUNCTYPE(None, _LRESULT, c_void_p))
    def _wkeWindowDestroyCallback(self, webview, param):
        if hasattr(self, 'wkeWindowDestroyCallback'):
            param = self.get_param_value(param)
            self.wkeWindowDestroyCallback(webview=webview, param=param)
        user32.PostQuitMessage(0)

    @method(
        CFUNCTYPE(None, _LRESULT, c_void_p, _LRESULT, c_int, c_int, c_int,
                  c_int))
    def _wkePaintUpdatedCallback(self, webview, param, hdc, x, y, cx, cy):
        if hasattr(self, 'wkePaintUpdatedCallback'):
            param = self.get_param_value(param)
            self.wkePaintUpdatedCallback(webview=webview,
                                         param=param,
                                         hdc=hdc,
                                         x=x,
                                         y=y,
                                         cx=cx,
                                         cy=cy)

    @method(
        CFUNCTYPE(None, _LRESULT, c_void_p, _LRESULT, POINTER(wkeRect), c_int,
                  c_int))
    def _wkePaintBitUpdatedCallback(self, webview, param, buf, rect, width,
                                    height):
        param = self.get_param_value(param)
        if hasattr(self, 'wkePaintBitUpdatedCallback'):
            self.wkePaintBitUpdatedCallback(webview=webview,
                                            param=param,
                                            buf=buf,
                                            rect=rect,
                                            width=width,
                                            height=height)

    @method(CFUNCTYPE(None, _LRESULT, c_void_p, c_void_p))
    def _wkeDocumentReady2Callback(self, webview, param, frameId):
        if hasattr(self, 'wkeDocumentReady2Callback'):
            param = self.get_param_value(param)
            self.wkeDocumentReady2Callback(webview=webview,
                                           param=param,
                                           frameId=frameId)

    @method(
        CFUNCTYPE(_LRESULT, _LRESULT, c_void_p, c_int, c_void_p,
                  POINTER(wkeWindowFeatures)))
    def _wkeCreateViewCallback(self, webview, param, navigationType, url,
                               windowFeatures):

        if hasattr(self, 'wkeCreateViewCallback'):
            url = self.mb.wkeGetStringW(url)
            param = self.get_param_value(param)
            return self.wkeCreateViewCallback(webview=webview,
                                              param=param,
                                              navigationType=navigationType,
                                              url=url,
                                              windowFeatures=windowFeatures)
        return 0

    @method(CFUNCTYPE(None, _LRESULT, c_void_p, c_int, c_void_p))
    def _wkeNavigationCallback(self, webview, param, navigationType, url):

        if hasattr(self, 'wkeNavigationCallback'):
            url = self.mb.wkeGetStringW(url)
            param = self.get_param_value(param)
            self.wkeNavigationCallback(webview=webview,
                                       param=param,
                                       navigationType=navigationType,
                                       url=url)

    @method(CFUNCTYPE(None, _LRESULT, c_void_p, c_void_p))
    def _wkeTitleChangedCallback(self, webview, param, title):
        if hasattr(self, 'wkeTitleChangedCallback'):
            title = self.mb.wkeGetStringW(title)
            param = self.get_param_value(param)
            self.wkeTitleChangedCallback(webview=webview,
                                         param=param,
                                         title=title)

    @method(CFUNCTYPE(None, _LRESULT, c_void_p, c_void_p))
    def _wkeMouseOverUrlChangedCallback(self, webview, param, url):

        if hasattr(self, 'wkeMouseOverUrlChangedCallback'):
            url = self.mb.wkeGetStringW(url)
            param = self.get_param_value(param)
            self.wkeMouseOverUrlChangedCallback(webview=webview,
                                                param=param,
                                                url=url)

    @method(CFUNCTYPE(None, _LRESULT, c_void_p, c_int, c_void_p))
    def _wkeURLChangedCallback2(self, webview, param, frameId, url):

        if hasattr(self, 'wkeURLChangedCallback2'):
            url = self.mb.wkeGetStringW(url)
            param = self.get_param_value(param)
            self.wkeURLChangedCallback2(webview=webview,
                                        param=param,
                                        frameId=frameId,
                                        url=url)

    @method(CFUNCTYPE(None, _LRESULT, c_void_p, c_void_p))
    def _wkeAlertBoxCallback(self, webview, param, msg):

        if hasattr(self, 'wkeAlertBoxCallback'):
            msg = self.mb.wkeGetStringW(msg)
            param = self.get_param_value(param)
            self.wkeAlertBoxCallback(webview=webview, param=param, msg=msg)

    @method(CFUNCTYPE(c_bool, _LRESULT, c_void_p, c_void_p))
    def _wkeConfirmBoxCallback(self, webview, param, msg):

        if hasattr(self, 'wkeConfirmBoxCallback'):
            msg = self.mb.wkeGetStringW(msg)
            param = self.get_param_value(param)
            return self.wkeConfirmBoxCallback(webview=webview,
                                              param=param,
                                              msg=msg)
        return False

    @method(CFUNCTYPE(c_bool, _LRESULT, c_void_p, c_void_p, c_void_p,
                      c_void_p))
    def _wkePromptBoxCallback(self, webview, param, msg, defaultResult,
                              result):

        if hasattr(self, 'wkePromptBoxCallback'):
            msg = self.mb.wkeGetStringW(msg)
            defaultResult = self.mb.wkeGetStringW(defaultResult)
            param = self.get_param_value(param)
            return self.wkePromptBoxCallback(webview=webview,
                                             param=param,
                                             msg=msg,
                                             defaultResult=defaultResult,
                                             result=result)
        return False

    @method(
        CFUNCTYPE(None, _LRESULT, c_void_p, c_int, c_void_p, c_void_p,
                  c_ulonglong, c_void_p))
    def _wkeConsoleCallback(self, webview, param, level, msg, sourceName,
                            sourceLine, stackTrace):

        if hasattr(self, 'wkeConsoleCallback'):
            msg = self.mb.wkeGetStringW(msg)
            sourceName = self.mb.wkeGetStringW(sourceName)
            stackTrace = self.mb.wkeGetStringW(stackTrace)
            param = self.get_param_value(param)
            self.wkeConsoleCallback(webview=webview,
                                    param=param,
                                    level=level,
                                    msg=msg,
                                    sourceName=sourceName,
                                    sourceLine=sourceLine,
                                    stackTrace=stackTrace)

    @method(CFUNCTYPE(c_bool, _LRESULT, c_void_p, c_char_p))
    def _wkeDownloadCallback(self, webview, param, url):

        if hasattr(self, 'wkeDownloadCallback'):
            url = url.decode()
            param = self.get_param_value(param)
            self.wkeDownloadCallback(webview=webview, param=param, url=url)
        return True

    @method(CFUNCTYPE(c_bool, _LRESULT, c_void_p, c_char_p, c_void_p))
    def _wkeNetResponseCallback(self, webview, param, url, job):

        if hasattr(self, 'wkeNetResponseCallback'):
            url = url.decode()
            param = self.get_param_value(param)
            return self.wkeNetResponseCallback(webview=webview,
                                               param=param,
                                               url=url,
                                               job=job)
        return False

    @method(CFUNCTYPE(c_bool, _LRESULT, c_void_p, c_char_p, c_void_p))
    def _wkeLoadUrlBeginCallback(self, webview, param, url, job):

        if hasattr(self, 'wkeLoadUrlBeginCallback'):
            url = url.decode()
            param = self.get_param_value(param)
            return self.wkeLoadUrlBeginCallback(webview=webview,
                                                param=param,
                                                url=url,
                                                job=job)
        return False

    @method(
        CFUNCTYPE(None, _LRESULT, c_void_p, c_char_p, c_void_p, c_void_p,
                  c_int))
    def _wkeLoadUrlEndCallback(self, webview, param, url, job, buf, lens):
        if hasattr(self, 'wkeLoadUrlEndCallback'):
            url = url.decode()
            param = self.get_param_value(param)
            self.wkeLoadUrlEndCallback(webview=webview,
                                       param=param,
                                       url=url,
                                       job=job,
                                       buf=buf,
                                       lens=lens)

    @method(CFUNCTYPE(None, _LRESULT, c_void_p, c_char_p, c_void_p))
    def _wkeLoadUrlFailCallback(self, webview, param, url, job):
        if hasattr(self, 'wkeLoadUrlFailCallback'):
            url = url.decode()
            param = self.get_param_value(param)
            self.wkeLoadUrlFailCallback(webview=webview,
                                        param=param,
                                        url=url,
                                        job=job)

    @method(CFUNCTYPE(None, _LRESULT, c_void_p, c_void_p, c_int, c_void_p))
    def _wkeLoadingFinishCallback(self, webview, param, url, result,
                                  failedReason):
        if hasattr(self, 'wkeLoadingFinishCallback'):
            url = self.mb.wkeGetStringW(url)
            if result == 1:
                failedReason = self.mb.wkeGetStringW(failedReason)
            param = self.get_param_value(param)
            self.wkeLoadingFinishCallback(webview=webview,
                                          param=param,
                                          url=url,
                                          result=result,
                                          failedReason=failedReason)

    @method(CFUNCTYPE(None, _LRESULT, c_void_p, c_char_p, POINTER(wkeMemBuf)))
    def _wkeOnNetGetFaviconCallback(self, webview, param, url, buf):
        if hasattr(self, 'wkeOnNetGetFaviconCallback'):
            url = url.decode()
            param = self.get_param_value(param)
            self.wkeOnNetGetFaviconCallback(webview=webview,
                                            param=param,
                                            url=url,
                                            buf=buf)

    def param_to_string(self, param):
        if param != 0:
            _type = 0
            if isinstance(param, str):
                _type = '1'
            elif isinstance(param, int):
                _type = '2'
            elif isinstance(param, float):
                _type = '3'
            elif isinstance(param, list):
                _type = '4'
            elif isinstance(param, tuple):
                _type = '5'
                param = list(param)
            elif isinstance(param, dict):
                _type = '6'
            else:
                param = 0
            if _type in ['4', '5', '6']:
                param = json.dumps(param)
            if _type != 0:
                param = f'{_type}-|-lochen-119182686-|-{param}'
                param = self.mb.wkeCreateStringW(param, len(param))
        return param

    def get_param_value(self, param):
        if param != None:
            param_str = self.mb.wkeGetStringW(param)
            ls = param_str.split('-|-lochen-119182686-|-')
            _type = ls[0]
            _param = ls[1]
            if _type == '1':
                ...
            elif _type == '2':
                _param = int(_param)
            elif _type == '3':
                _param = float(_param)
            elif _type in ['4', '5', '6']:
                _param = json.loads(_param)
            if _type == '5':
                _param = tuple(_param)
            return _param
Example #17
0
class MPIMsg(CompositeObject):

    _C_field_bufs = 'bufs'
    _C_field_bufg = 'bufg'
    _C_field_sizes = 'sizes'
    _C_field_rrecv = 'rrecv'
    _C_field_rsend = 'rsend'

    if MPI._sizeof(MPI.Request) == sizeof(c_int):
        c_mpirequest_p = type('MPI_Request', (c_int,), {})
    else:
        c_mpirequest_p = type('MPI_Request', (c_void_p,), {})

    fields = [
        (_C_field_bufs, c_void_p),
        (_C_field_bufg, c_void_p),
        (_C_field_sizes, POINTER(c_int)),
        (_C_field_rrecv, c_mpirequest_p),
        (_C_field_rsend, c_mpirequest_p),
    ]

    def __init__(self, name, function, halos):
        self._function = function
        self._halos = halos

        super(MPIMsg, self).__init__(name, 'msg', self.fields)

        # Required for buffer allocation/deallocation before/after jumping/returning
        # to/from C-land
        self._allocator = default_allocator()
        self._memfree_args = []

    def __del__(self):
        self._C_memfree()

    def _C_memfree(self):
        # Deallocate the MPI buffers
        for i in self._memfree_args:
            self._allocator.free(*i)
        self._memfree_args[:] = []

    def __value_setup__(self, dtype, value):
        # We eventually produce an array of `struct msg` that is as big as
        # the number of peers we have to communicate with
        return (dtype._type_*self.npeers)()

    @property
    def function(self):
        return self._function

    @property
    def halos(self):
        return self._halos

    @property
    def npeers(self):
        return len(self._halos)

    def _arg_defaults(self, alias=None):
        function = alias or self.function
        for i, halo in enumerate(self.halos):
            entry = self.value[i]
            # Buffer size for this peer
            shape = []
            for dim, side in zip(*halo):
                try:
                    shape.append(getattr(function._size_owned[dim], side.name))
                except AttributeError:
                    assert side is CENTER
                    shape.append(function._size_domain[dim])
            entry.sizes = (c_int*len(shape))(*shape)
            # Allocate the send/recv buffers
            size = reduce(mul, shape)
            ctype = dtype_to_ctype(function.dtype)
            entry.bufg, bufg_memfree_args = self._allocator._alloc_C_libcall(size, ctype)
            entry.bufs, bufs_memfree_args = self._allocator._alloc_C_libcall(size, ctype)
            # The `memfree_args` will be used to deallocate the buffer upon returning
            # from C-land
            self._memfree_args.extend([bufg_memfree_args, bufs_memfree_args])

        return {self.name: self.value}

    def _arg_values(self, args=None, **kwargs):
        return self._arg_defaults(alias=kwargs.get(self.function.name, self.function))

    def _arg_apply(self, *args, **kwargs):
        self._C_memfree()

    # Pickling support
    _pickle_args = ['name', 'function', 'halos']
Example #18
0
        """
        clibrebound.reb_integrator_synchronize(byref(self))


# Setting up fields after class definition (because of self-reference)
Simulation._fields_ = [
    ("t", c_double),
    ("G", c_double),
    ("softening", c_double),
    ("dt", c_double),
    ("dt_last_done", c_double),
    ("N", c_int),
    ("N_var", c_int),
    ("N_active", c_int),
    ("allocated_N", c_int),
    ("_particles", POINTER(Particle)),
    ("gravity_cs", POINTER(reb_vec3d)),
    ("gravity_cs_allocatedN", c_int),
    ("tree_root", c_void_p),
    ("tree_needs_update", c_int),
    ("opening_angle2", c_double),
    ("_status", c_int),
    ("exact_finish_time", c_int),
    ("force_is_velocity_dependent", c_uint),
    ("gravity_ignore_10", c_uint),
    ("output_timing_last", c_double),
    ("exit_max_distance", c_double),
    ("exit_min_distance", c_double),
    ("usleep", c_double),
    ("boxsize", reb_vec3d),
    ("boxsize_max", c_double),
Example #19
0
class reb_dp7(Structure):
    _fields_ = [("p0", POINTER(c_double)), ("p1", POINTER(c_double)),
                ("p2", POINTER(c_double)), ("p3", POINTER(c_double)),
                ("p4", POINTER(c_double)), ("p5", POINTER(c_double)),
                ("p6", POINTER(c_double))]
Example #20
0
def _cast_bytes(s, encoding='utf8'):
    if isinstance(s, unicode):
        return s.encode(encoding)
    return s


LIBPAM = CDLL(find_library("pam"))
LIBC = CDLL(find_library("c"))

CALLOC = LIBC.calloc
CALLOC.restype = c_void_p
CALLOC.argtypes = [c_uint, c_uint]

STRDUP = LIBC.strdup
STRDUP.argstypes = [c_char_p]
STRDUP.restype = POINTER(c_char) # NOT c_char_p !!!!

# Various constants
PAM_PROMPT_ECHO_OFF = 1
PAM_PROMPT_ECHO_ON = 2
PAM_ERROR_MSG = 3
PAM_TEXT_INFO = 4

# These constants are libpam-specific
PAM_ESTABLISH_CRED = 0x0002
PAM_DELETE_CRED = 0x0004
PAM_REINITIALIZE_CRED = 0x0008
PAM_REFRESH_CRED = 0x0010

# constants for PAM_ variables for pam_set_item()
PAM_SERVICE = 1
Example #21
0
    def __init__(self, load_callback, arch):
        self._handle = _get_library(arch)
        
        self._handle.libqemu_init.argtypes = [_libqemu_load_func, _libqemu_store_func]
        self._handle.libqemu_init.restype = c_int 
        
        self._handle.libqemu_get_module.argtypes = []
        self._handle.libqemu_get_module.restype = LLVMModuleRef
        
        self._handle.libqemu_gen_intermediate_code.argtypes = [c_uint64, c_uint64, c_bool, POINTER(LLVMValueRef)]
        self._handle.libqemu_gen_intermediate_code.restype = c_int 
        
        self._handle.libqemu_raise_error.argtypes = [c_void_p, c_int]
        self._handle.libqemu_raise_error.restype = None
        
        self._handle.libqemu_get_target_name.argtypes = []
        self._handle.libqemu_get_target_name.restype = c_char_p

        self._load_callback = _libqemu_load_func(lambda env, addr, size, signed, code: load_callback(self, env, addr, size, signed, code))
        error = self._handle.libqemu_init(self._load_callback, _libqemu_store_func())
        if error != 0:
            raise LibqemuError(error)
        self.module = ModuleRef(self._handle.libqemu_get_module())
Example #22
0
import site
import glob


class VL53L1xError(RuntimeError):
    pass


class VL53L1xDistanceMode:
    SHORT = 1
    MEDIUM = 2
    LONG = 3


# Read/write function pointer types.
_I2C_READ_FUNC = CFUNCTYPE(c_int, c_ubyte, c_ubyte, POINTER(c_ubyte), c_ubyte)
_I2C_WRITE_FUNC = CFUNCTYPE(c_int, c_ubyte, c_ubyte, POINTER(c_ubyte), c_ubyte)

# Load VL53L1X shared lib
_POSSIBLE_LIBRARY_LOCATIONS = [os.path.dirname(os.path.realpath(__file__))]

try:
    _POSSIBLE_LIBRARY_LOCATIONS += site.getsitepackages()
except AttributeError:
    pass

try:
    _POSSIBLE_LIBRARY_LOCATIONS += [site.getusersitepackages()]
except AttributeError:
    pass
Example #23
0
def all_params(funit, out=None):
    '''
  Extract parameters for *all* records.
  Returns a dictionary similar to fstprm, only the entries are
  vectorized over all records instead of 1 record at a time.
  NOTE: This includes deleted records as well.  You can filter them out using
        the 'dltf' flag.
  '''
    from ctypes import cast
    import numpy as np
    # Get the raw (packed) parameters.
    index = librmn.file_index(funit)
    raw = []
    file_index_list = []
    pageno_list = []
    recno_list = []
    while index >= 0:
        f = file_table[index].contents
        for pageno in range(f.npages):
            page = f.dir_page[pageno].contents
            params = cast(page.dir.entry, POINTER(c_uint32))
            params = np.ctypeslib.as_array(params,
                                           shape=(ENTRIES_PER_PAGE, 9, 2))
            nent = page.dir.nent
            raw.append(params[:nent])
            recno_list.extend(list(range(nent)))
            pageno_list.extend([pageno] * nent)
            file_index_list.extend([index] * nent)
        index = f.link
    raw = np.concatenate(raw)
    # Start unpacking the pieces.
    # Reference structure (from qstdir.h):
    # 0      word deleted:1, select:7, lng:24, addr:32;
    # 1      word deet:24, nbits: 8, ni:   24, gtyp:  8;
    # 2      word nj:24,  datyp: 8, nk:   20, ubc:  12;
    # 3      word npas: 26, pad7: 6, ig4: 24, ig2a:  8;
    # 4      word ig1:  24, ig2b:  8, ig3:  24, ig2c:  8;
    # 5      word etik15:30, pad1:2, etik6a:30, pad2:2;
    # 6      word etikbc:12, typvar:12, pad3:8, nomvar:24, pad4:8;
    # 7      word ip1:28, levtyp:4, ip2:28, pad5:4;
    # 8      word ip3:28, pad6:4, date_stamp:32;
    nrecs = raw.shape[0]
    if out is None:
        out = {}
        out['lng'] = np.empty(nrecs, dtype='int32')
        out['dltf'] = np.empty(nrecs, dtype='ubyte')
        out['swa'] = np.empty(nrecs, dtype='uint32')
        out['deet'] = np.empty(nrecs, dtype='int32')
        out['nbits'] = np.empty(nrecs, dtype='byte')
        out['grtyp'] = np.empty(nrecs, dtype='|S1')
        out['ni'] = np.empty(nrecs, dtype='int32')
        out['nj'] = np.empty(nrecs, dtype='int32')
        out['datyp'] = np.empty(nrecs, dtype='ubyte')
        out['nk'] = np.empty(nrecs, dtype='int32')
        out['ubc'] = np.empty(nrecs, dtype='uint16')
        out['npas'] = np.empty(nrecs, dtype='int32')
        out['ig1'] = np.empty(nrecs, dtype='int32')
        out['ig2'] = np.empty(nrecs, dtype='int32')
        out['ig3'] = np.empty(nrecs, dtype='int32')
        out['ig4'] = np.empty(nrecs, dtype='int32')
        out['etiket'] = np.empty(nrecs, dtype='|S12')
        out['typvar'] = np.empty(nrecs, dtype='|S2')
        out['nomvar'] = np.empty(nrecs, dtype='|S4')
        out['ip1'] = np.empty(nrecs, dtype='int32')
        out['ip2'] = np.empty(nrecs, dtype='int32')
        out['ip3'] = np.empty(nrecs, dtype='int32')
        out['datev'] = np.empty(nrecs, dtype='int32')
        out['dateo'] = np.empty(nrecs, dtype='int32')
        out['xtra1'] = np.empty(nrecs, dtype='uint32')
        out['xtra2'] = np.empty(nrecs, dtype='uint32')
        out['xtra3'] = np.empty(nrecs, dtype='uint32')
        out['key'] = np.empty(nrecs, dtype='int32')

    temp8 = np.empty(nrecs, dtype='ubyte')
    temp32 = np.empty(nrecs, dtype='int32')

    np.divmod(raw[:, 0, 0], 2**24, temp8, out['lng'])
    np.divmod(temp8, 128, out['dltf'], temp8)
    out['swa'][:] = raw[:, 0, 1]
    np.divmod(raw[:, 1, 0], 256, out['deet'], out['nbits'])
    np.divmod(raw[:, 1, 1], 256, out['ni'], out['grtyp'].view('ubyte'))
    np.divmod(raw[:, 2, 0], 256, out['nj'], out['datyp'])
    np.divmod(raw[:, 2, 1], 4096, out['nk'], out['ubc'])
    out['npas'][:] = raw[:, 3, 0] // 64
    np.divmod(raw[:, 3, 1], 256, out['ig4'], temp32)
    out['ig2'][:] = (temp32 << 16)  # ig2a
    np.divmod(raw[:, 4, 0], 256, out['ig1'], temp32)
    out['ig2'] |= (temp32 << 8)  # ig2b
    np.divmod(raw[:, 4, 1], 256, out['ig3'], temp32)
    out['ig2'] |= temp32  # ig2c
    etik15 = raw[:, 5, 0] // 4
    etik6a = raw[:, 5, 1] // 4
    et = raw[:, 6, 0] // 256
    etikbc, _typvar = divmod(et, 4096)
    _nomvar = raw[:, 6, 1] // 256
    np.divmod(raw[:, 7, 0], 16, out['ip1'], temp8)
    out['ip2'][:] = raw[:, 7, 1] // 16
    out['ip3'][:] = raw[:, 8, 0] // 16
    date_stamp = raw[:, 8, 1]
    # Reassemble and decode.
    # (Based on fstd98.c)
    etiket_bytes = np.empty((nrecs, 12), dtype='ubyte')
    for i in range(5):
        etiket_bytes[:, i] = ((etik15 >> ((4 - i) * 6)) & 0x3f) + 32
    for i in range(5, 10):
        etiket_bytes[:, i] = ((etik6a >> ((9 - i) * 6)) & 0x3f) + 32
    etiket_bytes[:, 10] = ((etikbc >> 6) & 0x3f) + 32
    etiket_bytes[:, 11] = (etikbc & 0x3f) + 32
    out['etiket'][:] = etiket_bytes.flatten().view('|S12')
    nomvar_bytes = np.empty((nrecs, 4), dtype='ubyte')
    for i in range(4):
        nomvar_bytes[:, i] = ((_nomvar >> ((3 - i) * 6)) & 0x3f) + 32
    out['nomvar'][:] = nomvar_bytes.flatten().view('|S4')
    typvar_bytes = np.empty((nrecs, 2), dtype='ubyte')
    typvar_bytes[:, 0] = ((_typvar >> 6) & 0x3f) + 32
    typvar_bytes[:, 1] = ((_typvar & 0x3f)) + 32
    out['typvar'][:] = typvar_bytes.flatten().view('|S2')
    out['datev'][:] = (date_stamp >> 3) * 10 + (date_stamp & 0x7)
    # Note: this dateo calculation is based on my assumption that
    # the raw stamps increase in 5-second intervals.
    # Doing it this way to avoid a gazillion calls to incdat.
    date_stamp = date_stamp - (out['deet'] * out['npas']) // 5
    out['dateo'][:] = (date_stamp >> 3) * 10 + (date_stamp & 0x7)
    out['xtra1'][:] = out['datev']
    out['xtra2'][:] = 0
    out['xtra3'][:] = 0
    # Calculate the handles (keys)
    # Based on "MAKE_RND_HANDLE" macro in qstdir.h.
    out['key'][:] = (np.array(file_index_list) & 0x3FF) | (
        (np.array(recno_list) & 0x1FF) << 10) | (
            (np.array(pageno_list) & 0xFFF) << 19)

    return out
Example #24
0
# lng:       header length (in 64 bit units)
# addr:      address of directory page (origin 1, 64 bit units)
# reserved1: idrep (4 ascii char 'DIR0')
# reserved2: reserved (0)
# nxt_addr:  address of next directory page (origin 1, 64 bit units)
# nent:      number of entries in page
# chksum:    checksum (not valid when in core)
# page_no, record_no, file_index: handle templage
# entry:     (real allocated dimension will be ENTRIES_PER_PAGE * primary_len)


class full_dir_page(Structure):
    pass


page_ptr = POINTER(full_dir_page)
full_dir_page._fields_ = [
    ('next_page', page_ptr),
    ('prev_page', page_ptr),
    ('modified', c_int),
    ('true_file_index', c_int),
    ('dir', xdf_dir_page),
]


class file_record(Structure):
    _fields_ = [
        ('lng', word, 24),
        ('idtyp', word, 8),
        ('addr', word, 32),  #XDF record header
        ('data', word * 2),  # primary keys, info keys, data
Example #25
0
import salt.utils  # Can be removed once get_group_list is moved
from salt.ext.six.moves import range  # pylint: disable=import-error,redefined-builtin

# Import 3rd-party libs
from salt.ext import six

LIBPAM = CDLL(find_library('pam'))
LIBC = CDLL(find_library('c'))

CALLOC = LIBC.calloc
CALLOC.restype = c_void_p
CALLOC.argtypes = [c_uint, c_uint]

STRDUP = LIBC.strdup
STRDUP.argstypes = [c_char_p]
STRDUP.restype = POINTER(c_char)  # NOT c_char_p !!!!

# Various constants
PAM_PROMPT_ECHO_OFF = 1
PAM_PROMPT_ECHO_ON = 2
PAM_ERROR_MSG = 3
PAM_TEXT_INFO = 4


class PamHandle(Structure):
    '''
    Wrapper class for pam_handle_t
    '''
    _fields_ = [('handle', c_void_p)]

    def __init__(self):
Example #26
0
class reb_simulation_integrator_wh(Structure):
    _fields_ = [(("allocatedN"), c_int), ("eta", POINTER(c_double))]
def listobject(l):
    return cast(id(l), POINTER(PyListObject)).contents
Example #28
0
def geos_linestring_from_py(ob, update_geom=None, update_ndim=0):
    # If numpy is present, we use numpy.require to ensure that we have a
    # C-continguous array that owns its data. View data will be copied.
    ob = required(ob)
    try:
        # From array protocol
        array = ob.__array_interface__
        assert len(array['shape']) == 2
        m = array['shape'][0]
        if m < 2:
            raise ValueError(
                "LineStrings must have at least 2 coordinate tuples")
        try:
            n = array['shape'][1]
        except IndexError:
            raise ValueError("Input %s is the wrong shape for a LineString" %
                             str(ob))
        assert n == 2 or n == 3

        # Make pointer to the coordinate array
        if isinstance(array['data'], tuple):
            # numpy tuple (addr, read-only)
            cp = cast(array['data'][0], POINTER(c_double))
        else:
            cp = array['data']

        # Create a coordinate sequence
        if update_geom is not None:
            cs = lgeos.GEOSGeom_getCoordSeq(update_geom)
            if n != update_ndim:
                raise ValueError(
                    "Wrong coordinate dimensions; this geometry has "
                    "dimensions: %d" % update_ndim)
        else:
            cs = lgeos.GEOSCoordSeq_create(m, n)

        # add to coordinate sequence
        for i in range(m):
            dx = c_double(cp[n * i])
            dy = c_double(cp[n * i + 1])
            dz = None
            if n == 3:
                try:
                    dz = c_double(cp[n * i + 2])
                except IndexError:
                    raise ValueError("Inconsistent coordinate dimensionality")

            # Because of a bug in the GEOS C API,
            # always set X before Y
            lgeos.GEOSCoordSeq_setX(cs, i, dx)
            lgeos.GEOSCoordSeq_setY(cs, i, dy)
            if n == 3:
                lgeos.GEOSCoordSeq_setZ(cs, i, dz)

    except AttributeError:
        # Fall back on list
        try:
            m = len(ob)
        except TypeError:  # Iterators, e.g. Python 3 zip
            ob = list(ob)
            m = len(ob)

        if m < 2:
            raise ValueError(
                "LineStrings must have at least 2 coordinate tuples")
        try:
            n = len(ob[0])
        except TypeError:
            raise ValueError("Input %s is the wrong shape for a LineString" %
                             str(ob))
        assert n == 2 or n == 3

        # Create a coordinate sequence
        if update_geom is not None:
            cs = lgeos.GEOSGeom_getCoordSeq(update_geom)
            if n != update_ndim:
                raise ValueError(
                    "Wrong coordinate dimensions; this geometry has "
                    "dimensions: %d" % update_ndim)
        else:
            cs = lgeos.GEOSCoordSeq_create(m, n)

        # add to coordinate sequence
        for i in range(m):
            coords = ob[i]
            # Because of a bug in the GEOS C API,
            # always set X before Y
            lgeos.GEOSCoordSeq_setX(cs, i, coords[0])
            lgeos.GEOSCoordSeq_setY(cs, i, coords[1])
            if n == 3:
                try:
                    lgeos.GEOSCoordSeq_setZ(cs, i, coords[2])
                except IndexError:
                    raise ValueError("Inconsistent coordinate dimensionality")

    if update_geom is not None:
        return None
    else:
        return lgeos.GEOSGeom_createLineString(cs), n
Example #29
0
LIBC = cdll.LoadLibrary(find_library("c"))

LIBC.ioctl.argtypes = [c_int, c_ulong, c_char_p]
LIBC.ioctl.restype = c_int

# The following is implemented as of Python >= 3.3
# under socket.*. Remember to use them when dropping Py2.7

# See https://docs.python.org/3/library/socket.html#socket.if_nameindex


class if_nameindex(Structure):
    _fields_ = [("if_index", c_uint), ("if_name", c_char_p)]


_ptr_ifnameindex_table = POINTER(if_nameindex * 255)

LIBC.if_nameindex.argtypes = []
LIBC.if_nameindex.restype = _ptr_ifnameindex_table
LIBC.if_freenameindex.argtypes = [_ptr_ifnameindex_table]
LIBC.if_freenameindex.restype = None

# Addresses manipulation functions


def get_if_raw_addr(ifname):
    """Returns the IPv4 address configured on 'ifname', packed with inet_pton."""  # noqa: E501

    ifname = network_name(ifname)

    # Get ifconfig output
Example #30
0
class ndpi_subprotocol_conf_struct(Structure):
    _fields_ = [("func",
                 CFUNCTYPE(c_void_p, POINTER(ndpi_detection_module_struct),
                           c_char_p, c_char_p, c_int))]
Example #31
0
    PVOID = c_void_p

    # --- Union inside Structure by stackoverflow:3480240 ---
    class _OFFSET(Structure):
        _fields_ = [('Offset', DWORD), ('OffsetHigh', DWORD)]

    class _OFFSET_UNION(Union):
        _anonymous_ = ['_offset']
        _fields_ = [('_offset', _OFFSET), ('Pointer', PVOID)]

    class OVERLAPPED(Structure):
        _anonymous_ = ['_offset_union']
        _fields_ = [('Internal', ULONG_PTR), ('InternalHigh', ULONG_PTR),
                    ('_offset_union', _OFFSET_UNION), ('hEvent', HANDLE)]

    LPOVERLAPPED = POINTER(OVERLAPPED)

    # --- Define function prototypes for extra safety ---
    LockFileEx = windll.kernel32.LockFileEx
    LockFileEx.restype = BOOL
    LockFileEx.argtypes = [HANDLE, DWORD, DWORD, DWORD, DWORD, LPOVERLAPPED]
    UnlockFileEx = windll.kernel32.UnlockFileEx
    UnlockFileEx.restype = BOOL
    UnlockFileEx.argtypes = [HANDLE, DWORD, DWORD, DWORD, LPOVERLAPPED]

    def lock(f, flags):
        hfile = msvcrt.get_osfhandle(_fd(f))
        overlapped = OVERLAPPED()
        ret = LockFileEx(hfile, flags, 0, 0, 0xFFFF0000, byref(overlapped))
        return bool(ret)
Example #32
0
def _RAMPPTR(cls):
    cls = POINTER(cls)
    cls.from_param = classmethod(cast_from_tuple(cls.from_param))
    return cls
Example #33
0
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.

import random
import logging
from threading import Thread
from ctypes import WINFUNCTYPE, POINTER
from ctypes import c_bool, c_int, create_unicode_buffer

from lib.common.abstracts import Auxiliary
from lib.common.defines import KERNEL32, USER32
from lib.common.defines import WM_GETTEXT, WM_GETTEXTLENGTH, WM_CLOSE, BM_CLICK

log = logging.getLogger(__name__)

EnumWindowsProc = WINFUNCTYPE(c_bool, POINTER(c_int), POINTER(c_int))
EnumChildProc = WINFUNCTYPE(c_bool, POINTER(c_int), POINTER(c_int))

RESOLUTION = {
    "x": USER32.GetSystemMetrics(0),
    "y": USER32.GetSystemMetrics(1)
}

def foreach_child(hwnd, lparam):
    # List of buttons labels to click.
    buttons = [
        "yes",
        "ok",
        "accept",
        "next",
        "install",
CoreFoundation = CDLL(core_foundation_path, use_errno=True)

CFIndex = c_long
CFStringEncoding = c_uint32
CFArray = c_void_p
CFData = c_void_p
CFString = c_void_p
CFNumber = c_void_p
CFDictionary = c_void_p
CFError = c_void_p
CFType = c_void_p
CFTypeID = c_ulong
CFBoolean = c_void_p
CFNumberType = c_uint32

CFTypeRef = POINTER(CFType)
CFArrayRef = POINTER(CFArray)
CFDataRef = POINTER(CFData)
CFStringRef = POINTER(CFString)
CFNumberRef = POINTER(CFNumber)
CFBooleanRef = POINTER(CFBoolean)
CFDictionaryRef = POINTER(CFDictionary)
CFErrorRef = POINTER(CFError)
CFAllocatorRef = c_void_p
CFDictionaryKeyCallBacks = c_void_p
CFDictionaryValueCallBacks = c_void_p
CFArrayCallBacks = c_void_p

pointer_p = POINTER(c_void_p)

try:
Example #35
0
from ctypes.wintypes import DWORD, LPVOID, BOOL, HANDLE, WORD

from .. import CEnum, windll
from ..shared.ntdef import PVOID
from ..shared.basetsd import ULONG_PTR


class SECURITY_ATTRIBUTES(Structure):
    _fields_ = [
        ("nLength", DWORD),
        ("lpSecurityDescriptor", LPVOID),
        ("bInheritHandle", BOOL),
    ]


LPSECURITY_ATTRIBUTES = POINTER(SECURITY_ATTRIBUTES)


class OVERLAPPED_STRUCT(Structure):
    _fields_ = [
        ("Offset", DWORD),
        ("OffsetHigh", DWORD),
    ]


class OVERLAPPED_UNION(Union):
    _anonymous_ = ("u", )
    _fields_ = [
        ("u", OVERLAPPED_STRUCT),
        ("Pointer", PVOID),
    ]
Example #36
0
class struct_ndpi_int_one_line_struct(Structure):
    _fields_ = [
        ('ptr', POINTER(c_uint8)),
        ('len', c_uint16),
    ]
Example #37
0
FT_Int = c_int
FT_UInt = c_uint
FT_F2Dot14 = c_short
FT_Pos = FT_Fixed = FT_Long = c_long
FT_Glyph_Format = c_int
FT_String_p = c_char_p
FT_Short = c_short  # A typedef for signed short.
FT_UShort = c_ushort  # A typedef for unsigned short.
FT_Generic_Finalizer = CFUNCTYPE(None, c_void_p)
FT_Encoding = c_int


class FT_LibraryRec(Structure):
    _fields_ = []
FT_Library = POINTER(FT_LibraryRec)


class FT_Vector(Structure):
    _fields_ = [('x', FT_Pos), ('y', FT_Pos)]


class FT_UnitVector(Structure):
    _fields_ = [('x', FT_F2Dot14), ('y', FT_F2Dot14)]


class FT_Matrix(Structure):
    _fields_ = [('xx', FT_Fixed), ('xy', FT_Fixed),
                ('yx', FT_Fixed), ('yy', FT_Fixed)]

if not security_path:
    raise LibraryNotFoundError('The library Security could not be found')

Security = CDLL(security_path, use_errno=True)

Boolean = c_bool
CFIndex = c_long
CFData = c_void_p
CFString = c_void_p
CFArray = c_void_p
CFDictionary = c_void_p
CFError = c_void_p
CFType = c_void_p
CFTypeID = c_ulong

CFTypeRef = POINTER(CFType)
CFAllocatorRef = c_void_p

OSStatus = c_int32

CFDataRef = POINTER(CFData)
CFStringRef = POINTER(CFString)
CFArrayRef = POINTER(CFArray)
CFDictionaryRef = POINTER(CFDictionary)
CFErrorRef = POINTER(CFError)

SecKeyRef = POINTER(c_void_p)
SecCertificateRef = POINTER(c_void_p)
SecTransformRef = POINTER(c_void_p)
SecRandomRef = c_void_p
SecTrustSettingsDomain = c_uint32
Example #39
0
def _POINTER(cls):
    cls = POINTER(cls)
    cls.from_param = classmethod(allow_void_p_param(cls.from_param))
    cls.get_void_p = get_void_p
    return cls
Example #40
0
 def fn():
     p = POINTER(c_double)()
     p.contents = c_double(6.1)
     return p.contents.value
Example #41
0
                           c_char_p, c_char_p, c_int))]


class ndpi_automa(Structure):
    _fields_ = [
        ("ac_automa", c_void_p),  #Real type is AC_AUTOMATA_t
        ("ac_automa_finalized", c_uint8)
    ]


class struct_node_t(Structure):
    pass


struct_node_t._fields_ = [
    ('key', POINTER(c_char)),
    ('left', POINTER(struct_node_t)),
    ('right', POINTER(struct_node_t)),
]


class ndpi_call_function_struct(Structure):
    _fields_ = [("detection_bitmask", NDPI_PROTOCOL_BITMASK),
                ("excluded_protocol_bitmask", NDPI_PROTOCOL_BITMASK),
                ("ndpi_selection_bitmask", c_uint32),
                ("func",
                 CFUNCTYPE(None, POINTER(ndpi_detection_module_struct),
                           POINTER(ndpi_flow_struct))),
                ("detection_feature", c_uint8)]

Example #42
0
class hash_ip4p(Structure):
    _fields_ = [("top", POINTER(hash_ip4p_node)), ("lock", spinlock_t),
                ("len", c_size_t)]
Example #43
0
    c_size_t,  # size_t         inbuflen
    c_char_p,  # uint8_t       *outbuf
    c_char_p,  # const uint8_t *passwd
    c_size_t,  # size_t         passwdlen
    c_size_t,  # size_t         maxmem
    c_double,  # double         maxmemfrac
    c_double,  # double         maxtime
]
_scryptenc_buf.restype = c_int

_scryptdec_buf = _scrypt.exp_scryptdec_buf
_scryptdec_buf.argtypes = [
    c_char_p,  # const uint8_t *inbuf
    c_size_t,  # size_t         inbuflen
    c_char_p,  # uint8_t       *outbuf
    POINTER(c_size_t),  # size_t        *outlen
    c_char_p,  # const uint8_t *passwd
    c_size_t,  # size_t         passwdlen
    c_size_t,  # size_t         maxmem
    c_double,  # double         maxmemfrac
    c_double,  # double         maxtime
]
_scryptdec_buf.restype = c_int

_crypto_scrypt = _scrypt.exp_crypto_scrypt
_crypto_scrypt.argtypes = [
    c_char_p,  # const uint8_t *passwd
    c_size_t,  # size_t         passwdlen
    c_char_p,  # const uint8_t *salt
    c_size_t,  # size_t         saltlen
    c_uint64,  # uint64_t       N
Example #44
0
class ndpi_lru_cache(Structure):  # 192 bytes
    _fields_ = [
        ("num_entries", c_uint32),
        ("entries", POINTER(c_uint32)),
    ]
Example #45
0
 def fn():
     p = POINTER(c_int)()
     assert not p
     p.contents = c_int(12)
     assert p
        ('data', POINTER(c_uint8)),
        ('size', c_int),
        ('type', c_int)
    ]


AVBufferRef = libavutil.AVBufferRef

AVRational = libavutil.AVRational


class AVPacket(Structure):
    pass

AVPacket_Fields = [
        ('buf', POINTER(AVBufferRef)),
        ('pts', c_int64),
        ('dts', c_int64),
        ('data', POINTER(c_uint8)),
        ('size', c_int),
        ('stream_index', c_int),
        ('flags', c_int),
        ('side_data', POINTER(AVPacketSideData)),
        ('side_data_elems', c_int),
        ('duration', c_int64),
        ('pos', c_int64),
        ('opaque', c_void_p),  # 5.x only
        ('opaque_ref', c_void_p),  # 5.x only
        ('time_base', AVRational),  # 5.x only
        ('convergence_duration', c_int64)  # 4.x only
    ]
Example #47
0
CFData = c_void_p
CFString = c_void_p
CFArray = c_void_p
CFMutableArray = c_void_p
CFDictionary = c_void_p
CFError = c_void_p
CFType = c_void_p
CFTypeID = c_ulong

CFTypeRef = POINTER(CFType)
CFAllocatorRef = c_void_p

OSStatus = c_int32

CFDataRef = POINTER(CFData)
CFStringRef = POINTER(CFString)
CFArrayRef = POINTER(CFArray)
CFMutableArrayRef = POINTER(CFMutableArray)
CFDictionaryRef = POINTER(CFDictionary)
CFArrayCallBacks = c_void_p
CFDictionaryKeyCallBacks = c_void_p
CFDictionaryValueCallBacks = c_void_p

SecCertificateRef = POINTER(c_void_p)
SecExternalFormat = c_uint32
SecExternalItemType = c_uint32
SecIdentityRef = POINTER(c_void_p)
SecItemImportExportFlags = c_uint32
SecItemImportExportKeyParameters = c_void_p
SecKeychainRef = POINTER(c_void_p)
SSLProtocol = c_uint32
class AVPacketSideData(Structure):
    _fields_ = [
        ('data', POINTER(c_uint8)),
        ('size', c_int),
        ('type', c_int)
    ]
Example #49
0
Security = CDLL(security_path, use_errno=True)
CoreFoundation = CDLL(core_foundation_path, use_errno=True)

Boolean = c_bool
CFIndex = c_long
CFStringEncoding = c_uint32
CFData = c_void_p
CFString = c_void_p
CFArray = c_void_p
CFMutableArray = c_void_p
CFDictionary = c_void_p
CFError = c_void_p
CFType = c_void_p
CFTypeID = c_ulong

CFTypeRef = POINTER(CFType)
CFAllocatorRef = c_void_p

OSStatus = c_int32

CFDataRef = POINTER(CFData)
CFStringRef = POINTER(CFString)
CFArrayRef = POINTER(CFArray)
CFMutableArrayRef = POINTER(CFMutableArray)
CFDictionaryRef = POINTER(CFDictionary)
CFArrayCallBacks = c_void_p
CFDictionaryKeyCallBacks = c_void_p
CFDictionaryValueCallBacks = c_void_p

SecCertificateRef = POINTER(c_void_p)
SecExternalFormat = c_uint32
Example #50
0
 def fn():
     p = POINTER(c_double)()
     p.contents = c_double(6.25)
     return p