Python ctypes.c_ulong() Examples

The following are 30 code examples of ctypes.c_ulong(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ctypes , or try the search function .
Example #1
Source File: gen.py    From multibootusb with GNU General Public License v2.0 12 votes vote down vote up
def windowsRam(self):
        """
        Uses Windows API to check RAM
        """
        kernel32 = ctypes.windll.kernel32
        c_ulong = ctypes.c_ulong

        class MEMORYSTATUS(ctypes.Structure):
            _fields_ = [
                ("dwLength", c_ulong),
                ("dwMemoryLoad", c_ulong),
                ("dwTotalPhys", c_ulong),
                ("dwAvailPhys", c_ulong),
                ("dwTotalPageFile", c_ulong),
                ("dwAvailPageFile", c_ulong),
                ("dwTotalVirtual", c_ulong),
                ("dwAvailVirtual", c_ulong)
            ]

        memoryStatus = MEMORYSTATUS()
        memoryStatus.dwLength = ctypes.sizeof(MEMORYSTATUS)
        kernel32.GlobalMemoryStatus(ctypes.byref(memoryStatus))

        return int(memoryStatus.dwTotalPhys / 1024 ** 2) 
Example #2
Source File: canlib.py    From Udacity-SDC-Radar-Driver-Micro-Challenge with MIT License 6 votes vote down vote up
def getChannelData_Chan_No_On_Card(self, channel):
        """Get the channel number on the card.
        Retrieves the channel number, as numbered locally on the card, device
        connected to channel.
        Args:
            channel (int): The channel you are interested in
        Returns:
            number (int): The local channel number
        """
        self.fn = inspect.currentframe().f_code.co_name
        number = ct.c_ulong()
        self.dll.canGetChannelData(channel,
                                   canCHANNELDATA_CHAN_NO_ON_CARD,
                                   ct.byref(number), ct.sizeof(number))
        buf_type = ct.c_uint * 1
        buf = buf_type()
        self.dll.canGetChannelData(channel,
                                   canCHANNELDATA_CHAN_NO_ON_CARD,
                                   ct.byref(buf), ct.sizeof(buf))
        return number.value 
Example #3
Source File: canlib.py    From Udacity-SDC-Radar-Driver-Micro-Challenge with MIT License 6 votes vote down vote up
def getChannelData_Chan_No_On_Card(self, channel):
        """Get the channel number on the card.
        Retrieves the channel number, as numbered locally on the card, device
        connected to channel.
        Args:
            channel (int): The channel you are interested in
        Returns:
            number (int): The local channel number
        """
        self.fn = inspect.currentframe().f_code.co_name
        number = ct.c_ulong()
        self.dll.canGetChannelData(channel,
                                   canCHANNELDATA_CHAN_NO_ON_CARD,
                                   ct.byref(number), ct.sizeof(number))
        buf_type = ct.c_uint * 1
        buf = buf_type()
        self.dll.canGetChannelData(channel,
                                   canCHANNELDATA_CHAN_NO_ON_CARD,
                                   ct.byref(buf), ct.sizeof(buf))
        return number.value 
Example #4
Source File: canlib.py    From Udacity-SDC-Radar-Driver-Micro-Challenge with MIT License 6 votes vote down vote up
def getChannelData_CardNumber(self, channel):
        """Get the card number
        Retrieves the card's number in the computer. Each card type is numbered
        separately. For example, the first PCIEcan card in a machine will have
        number 0, the second PCIEcan number 1, etc.
        Args:
            channel (int): The channel you are interested in
        Returns:
            card_number (int): The device's card number
        """
        self.fn = inspect.currentframe().f_code.co_name
        buf_type = ct.c_ulong
        buf = buf_type()
        self.dll.canGetChannelData(channel,
                                   canCHANNELDATA_CARD_NUMBER,
                                   ct.byref(buf), ct.sizeof(buf))
        return buf.value 
Example #5
Source File: canlib.py    From Udacity-SDC-Radar-Driver-Micro-Challenge with MIT License 6 votes vote down vote up
def getChannelData_EAN(self, channel):
        """Get EAN code
        Retrieves the EAN number for the device connected to channel. If there
        is no EAN number, "00-00000-00000-0" will be returned.
        Args:
            channel (int): The channel you are interested in
        Returns:
            ean (str): The device's EAN number
        """
        self.fn = inspect.currentframe().f_code.co_name
        buf_type = ct.c_ulong * 2
        buf = buf_type()
        self.dll.canGetChannelData(channel,
                                   canCHANNELDATA_CARD_UPC_NO,
                                   ct.byref(buf), ct.sizeof(buf))
        (ean_lo, ean_hi) = struct.unpack('LL', buf)

        return "%02x-%05x-%05x-%x" % (ean_hi >> 12,
                                      ((ean_hi & 0xfff) << 8) | (ean_lo >> 24),
                                      (ean_lo >> 4) & 0xfffff, ean_lo & 0xf) 
Example #6
Source File: canlib.py    From Udacity-SDC-Radar-Driver-Micro-Challenge with MIT License 6 votes vote down vote up
def getChannelData_EAN_short(self, channel):
        """Get short EAN code
        Retrieves the short EAN number, aka product number, for the device
        connected to channel. If there is no EAN number, "00000-0" will be
        returned.
        Args:
            channel (int): The channel you are interested in
        Returns:
            ean (str): The device's shortened EAN number
        """
        self.fn = inspect.currentframe().f_code.co_name
        buf_type = ct.c_ulong * 2
        buf = buf_type()
        self.dll.canGetChannelData(channel,
                                   canCHANNELDATA_CARD_UPC_NO,
                                   ct.byref(buf), ct.sizeof(buf))
        (ean_lo, ean_hi) = struct.unpack('LL', buf)
        return "%04x-%x" % ((ean_lo >> 4) & 0xffff, ean_lo & 0xf) 
Example #7
Source File: PlatformManagerWindows.py    From lackey with MIT License 6 votes vote down vote up
def getWindowByPID(self, pid, order=0):
        """ Returns a handle for the first window that matches the provided PID """
        if pid <= 0:
            return None
        EnumWindowsProc = ctypes.WINFUNCTYPE(
            ctypes.c_bool,
            ctypes.POINTER(ctypes.c_int),
            ctypes.py_object)
        def callback(hwnd, context):
            if ctypes.windll.user32.IsWindowVisible(hwnd):
                pid = ctypes.c_ulong()
                ctypes.windll.user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
                if context["pid"] == int(pid.value) and not context["handle"]:
                    if context["order"] > 0:
                        context["order"] -= 1
                    else:
                        context["handle"] = hwnd
            return True
        data = {"pid": pid, "handle": None, "order": order}
        ctypes.windll.user32.EnumWindows(EnumWindowsProc(callback), ctypes.py_object(data))
        return data["handle"] 
Example #8
Source File: canlib.py    From Udacity-SDC-Radar-Driver-Micro-Challenge with MIT License 6 votes vote down vote up
def getChannelData_Serial(self, channel):
        """Get device serial number
        Retrieves the serial number for the device connected to channel. If the
        device does not have a serial number, 0 is returned.
        Args:
            channel (int): The channel you are interested in
        Returns:
            serial (int): The device serial number
        """
        self.fn = inspect.currentframe().f_code.co_name
        buf_type = ct.c_ulong * 2
        buf = buf_type()
        self.dll.canGetChannelData(channel,
                                   canCHANNELDATA_CARD_SERIAL_NO,
                                   ct.byref(buf), ct.sizeof(buf))
        (serial_lo, serial_hi) = struct.unpack('LL', buf)
        # serial_hi is always 0
        return serial_lo 
Example #9
Source File: canlib.py    From Udacity-SDC-Radar-Driver-Micro-Challenge with MIT License 6 votes vote down vote up
def getChannelData_CardNumber(self, channel):
        """Get the card number
        Retrieves the card's number in the computer. Each card type is numbered
        separately. For example, the first PCIEcan card in a machine will have
        number 0, the second PCIEcan number 1, etc.
        Args:
            channel (int): The channel you are interested in
        Returns:
            card_number (int): The device's card number
        """
        self.fn = inspect.currentframe().f_code.co_name
        buf_type = ct.c_ulong
        buf = buf_type()
        self.dll.canGetChannelData(channel,
                                   canCHANNELDATA_CARD_NUMBER,
                                   ct.byref(buf), ct.sizeof(buf))
        return buf.value 
Example #10
Source File: canlib.py    From Udacity-SDC-Radar-Driver-Micro-Challenge with MIT License 6 votes vote down vote up
def getChannelData_EAN_short(self, channel):
        """Get short EAN code
        Retrieves the short EAN number, aka product number, for the device
        connected to channel. If there is no EAN number, "00000-0" will be
        returned.
        Args:
            channel (int): The channel you are interested in
        Returns:
            ean (str): The device's shortened EAN number
        """
        self.fn = inspect.currentframe().f_code.co_name
        buf_type = ct.c_ulong * 2
        buf = buf_type()
        self.dll.canGetChannelData(channel,
                                   canCHANNELDATA_CARD_UPC_NO,
                                   ct.byref(buf), ct.sizeof(buf))
        (ean_lo, ean_hi) = struct.unpack('LL', buf)
        return "%04x-%x" % ((ean_lo >> 4) & 0xffff, ean_lo & 0xf) 
Example #11
Source File: term.py    From xyppy with MIT License 6 votes vote down vote up
def getch_impl():
    # TODO: This windows impl keeps pipes/redirects from working. Need ReadFile for that,
    # with more complicated handling (personally, I'm just going to keep using unix/cygwin
    # for pipe-y debug stuff...)
    # TODO: Windows escape seqs via ReadConsoleInput, convert to VT100 seqs for more commonality.
    if is_windows:
        stdin_handle = ctypes.windll.kernel32.GetStdHandle(ctypes.c_ulong(-10))
        one_char_buf = ctypes.c_uint32()
        chars_read = ctypes.c_uint32()
        # NOTE: W version of this function == ERROR_NOACCESS after text color set in photopia!?
        result = ctypes.windll.kernel32.ReadConsoleA(stdin_handle,
                                                     ctypes.byref(one_char_buf),
                                                     1,
                                                     ctypes.byref(chars_read),
                                                     0)

        if result == 0 or chars_read.value != 1:
            last_err = ctypes.windll.kernel32.GetLastError()
            print('LAST ERR', last_err)
            err('failed to read console')

        return chr(one_char_buf.value)
    else: #Unix
        return sys.stdin.read(1) 
Example #12
Source File: term.py    From xyppy with MIT License 6 votes vote down vote up
def set_color(fg_col, bg_col):
    global last_fg_col
    global last_bg_col
    if fg_col == last_fg_col and bg_col == last_bg_col:
        return
    last_fg_col = fg_col
    last_bg_col = bg_col
    if is_windows:
        # convert from (rgb+2) to bgr
        fg_col = rgb3_to_bgr3(fg_col-2)
        bg_col = rgb3_to_bgr3(bg_col-2)
        col_attr = fg_col | (bg_col << 4)
        stdout_handle = ctypes.windll.kernel32.GetStdHandle(ctypes.c_ulong(-11))
        ctypes.windll.kernel32.SetConsoleTextAttribute(stdout_handle, col_attr)
    else:
        color = str(fg_col + 28)
        sys.stdout.write('\x1b['+color+'m')
        color = str(bg_col + 38)
        sys.stdout.write('\x1b['+color+'m')

# TODO: any other encodings to check for? 
Example #13
Source File: RATAttack.py    From RAT-via-Telegram with MIT License 6 votes vote down vote up
def get_curr_window():
		user32 = ctypes.windll.user32
		kernel32 = ctypes.windll.kernel32
		hwnd = user32.GetForegroundWindow()
		pid = ctypes.c_ulong(0)
		user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
		process_id = "%d" % pid.value
		executable = ctypes.create_string_buffer(512)
		h_process = kernel32.OpenProcess(0x400 | 0x10, False, pid)
		ctypes.windll.psapi.GetModuleBaseNameA(h_process, None, ctypes.byref(executable), 512)
		window_title = ctypes.create_string_buffer(512)
		length = user32.GetWindowTextA(hwnd, ctypes.byref(window_title), 512)
		pid_info = "\n[ PID %s - %s - %s ]" % (process_id, executable.value, window_title.value)
		kernel32.CloseHandle(hwnd)
		kernel32.CloseHandle(h_process)
		return pid_info 
Example #14
Source File: cgroups_allocations.py    From workload-collocation-agent with Apache License 2.0 6 votes vote down vote up
def _migrate_page_call(pid, max_node, old_nodes, new_node) -> int:
    """Wrapper on migrate_pages function using libc syscall"""

    pid = int(pid)
    max = ctypes.c_ulong(max_node + 1)
    old = ctypes.pointer(ctypes.c_ulong(old_nodes))
    new = ctypes.pointer(ctypes.c_ulong(new_node))

    # Example memory_migrate(256, pid, 5, 13 -> b'1101', 2 -> b'0010')
    result = LIBC.syscall(NR_MIGRATE_PAGES, pid, max, old, new)

    if result == -1:
        errno = ctypes.get_errno()
        raise UnableToMigratePages('Unable to migrate pages: {}, {}.'
                                   .format(errno, os.strerror(errno)))
    log.log(TRACE, 'Number of not moved pages (return from migrate_pages syscall): %d', result)
    return result 
Example #15
Source File: createminidump.py    From minidump with MIT License 6 votes vote down vote up
def enum_pids():
	
	max_array = c_ulong * 4096 # define long array to capture all the processes
	pProcessIds = max_array() # array to store the list of processes
	pBytesReturned = c_ulong() # the number of bytes returned in the array
	#EnumProcess 
	res = EnumProcesses(
		ctypes.byref(pProcessIds),
		ctypes.sizeof(pProcessIds),
		ctypes.byref(pBytesReturned)
	)
	if res == 0:
		logging.error(WinError(get_last_error()))
		return []
  
	# get the number of returned processes
	nReturned = int(pBytesReturned.value/ctypes.sizeof(c_ulong()))
	return [i for i in pProcessIds[:nReturned]]
	
#https://msdn.microsoft.com/en-us/library/windows/desktop/ms683217(v=vs.85).aspx 
Example #16
Source File: _win32.py    From dragonfly with GNU Lesser General Public License v3.0 6 votes vote down vote up
def execute(self, window):
        # Ensure that the primary mouse button is the *left* button before
        # sending events.
        primary_changed = windll.user32.SwapMouseButton(0)

        # Prepare and send the mouse events.
        zero = pointer(c_ulong(0))
        inputs = [MouseInput(0, 0, flag[1], flag[0], 0, zero)
                  for flag in self._flags]
        array = make_input_array(inputs)
        send_input_array(array)

        # Swap the primary mouse button back if it was previously set to
        # *right*.
        if primary_changed:
            windll.user32.SwapMouseButton(1) 
Example #17
Source File: canlib.py    From Udacity-SDC-Radar-Driver-Micro-Challenge with MIT License 6 votes vote down vote up
def getChannelData_EAN(self, channel):
        """Get EAN code
        Retrieves the EAN number for the device connected to channel. If there
        is no EAN number, "00-00000-00000-0" will be returned.
        Args:
            channel (int): The channel you are interested in
        Returns:
            ean (str): The device's EAN number
        """
        self.fn = inspect.currentframe().f_code.co_name
        buf_type = ct.c_ulong * 2
        buf = buf_type()
        self.dll.canGetChannelData(channel,
                                   canCHANNELDATA_CARD_UPC_NO,
                                   ct.byref(buf), ct.sizeof(buf))
        (ean_lo, ean_hi) = struct.unpack('LL', buf)

        return "%02x-%05x-%05x-%x" % (ean_hi >> 12,
                                      ((ean_hi & 0xfff) << 8) | (ean_lo >> 24),
                                      (ean_lo >> 4) & 0xfffff, ean_lo & 0xf) 
Example #18
Source File: directkeys.py    From pygta5 with GNU General Public License v3.0 5 votes vote down vote up
def ReleaseKey(hexKeyCode):
    extra = ctypes.c_ulong(0)
    ii_ = Input_I()
    ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )
    x = Input( ctypes.c_ulong(1), ii_ )
    ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x)) 
Example #19
Source File: directkeys.py    From pygta5 with GNU General Public License v3.0 5 votes vote down vote up
def PressKey(hexKeyCode):
    extra = ctypes.c_ulong(0)
    ii_ = Input_I()
    ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
    x = Input( ctypes.c_ulong(1), ii_ )
    ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x)) 
Example #20
Source File: winmake.py    From psutil with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def stderr_handle():
    GetStdHandle = ctypes.windll.Kernel32.GetStdHandle
    STD_ERROR_HANDLE_ID = ctypes.c_ulong(0xfffffff4)
    GetStdHandle.restype = ctypes.c_ulong
    handle = GetStdHandle(STD_ERROR_HANDLE_ID)
    atexit.register(ctypes.windll.Kernel32.CloseHandle, handle)
    return handle 
Example #21
Source File: directkeys.py    From pygta5 with GNU General Public License v3.0 5 votes vote down vote up
def PressKey(hexKeyCode):
    extra = ctypes.c_ulong(0)
    ii_ = Input_I()
    ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
    x = Input( ctypes.c_ulong(1), ii_ )
    ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x)) 
Example #22
Source File: simple_com.py    From LKD with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_c_callable(func, types, keepalive=[]):
    func_type = ctypes.WINFUNCTYPE(*types)
    c_callable = func_type(func)
    # Dirty, but other methods require native code execution
    c_callback_addr = ctypes.c_ulong.from_address(id(c_callable._objects['0']) + 3 * ctypes.sizeof(ctypes.c_void_p)).value
    keepalive.append(c_callable)
    return c_callback_addr 
Example #23
Source File: _common.py    From psutil with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def print_color(s, color=None, bold=False, file=sys.stdout):
    """Print a colorized version of string."""
    if not term_supports_colors():
        print(s, file=file)  # NOQA
    elif POSIX:
        print(hilite(s, color, bold), file=file)  # NOQA
    else:
        import ctypes

        DEFAULT_COLOR = 7
        GetStdHandle = ctypes.windll.Kernel32.GetStdHandle
        SetConsoleTextAttribute = \
            ctypes.windll.Kernel32.SetConsoleTextAttribute

        colors = dict(green=2, red=4, brown=6, yellow=6)
        colors[None] = DEFAULT_COLOR
        try:
            color = colors[color]
        except KeyError:
            raise ValueError("invalid color %r; choose between %r" % (
                color, list(colors.keys())))
        if bold and color <= 7:
            color += 8

        handle_id = -12 if file is sys.stderr else -11
        GetStdHandle.restype = ctypes.c_ulong
        handle = GetStdHandle(handle_id)
        SetConsoleTextAttribute(handle, color)
        try:
            print(s, file=file)    # NOQA
        finally:
            SetConsoleTextAttribute(handle, DEFAULT_COLOR) 
Example #24
Source File: cpuinfo.py    From py-cpuinfo with MIT License 5 votes vote down vote up
def free(self):
		# Free the function memory segment
		if DataSource.is_windows:
			MEM_RELEASE = ctypes.c_ulong(0x8000)
			ctypes.windll.kernel32.VirtualFree(ctypes.c_void_p(self.address), ctypes.c_size_t(0), MEM_RELEASE)
		else:
			self.mm.close()

		self.prochandle = None
		self.mm = None
		self.func = None
		self.address = None
		self.size = 0 
Example #25
Source File: __init__.py    From python-libxdo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def mouse_down(self, window, button):
        """
        Send a mouse press (aka mouse down) for a given button at
        the current mouse location.

        :param window:
            The window you want to send the event to or CURRENTWINDOW
        :param button:
            The mouse button. Generally, 1 is left, 2 is middle, 3 is
            right, 4 is wheel up, 5 is wheel down.
        """
        _libxdo.xdo_mouse_down(
            self._xdo, ctypes.c_ulong(window), ctypes.c_int(button)) 
Example #26
Source File: __init__.py    From python-libxdo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def mouse_up(self, window, button):
        """
        Send a mouse release (aka mouse up) for a given button at
        the current mouse location.

        :param window:
            The window you want to send the event to or CURRENTWINDOW
        :param button:
            The mouse button. Generally, 1 is left, 2 is middle, 3 is
            right, 4 is wheel up, 5 is wheel down.
        """
        _libxdo.xdo_mouse_up(
            self._xdo, ctypes.c_ulong(window), ctypes.c_int(button)) 
Example #27
Source File: PlatformManagerWindows.py    From lackey with MIT License 5 votes vote down vote up
def getWindowPID(self, hwnd):
        """ Gets the process ID that the specified window belongs to """
        pid = ctypes.c_ulong()
        ctypes.windll.user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
        return int(pid.value) 
Example #28
Source File: PlatformManagerWindows.py    From lackey with MIT License 5 votes vote down vote up
def isPIDValid(self, pid):
        """ Checks if a PID is associated with a running process """
        ## Slightly copied wholesale from http://stackoverflow.com/questions/568271/how-to-check-if-there-exists-a-process-with-a-given-pid
        ## Thanks to http://stackoverflow.com/users/1777162/ntrrgc and http://stackoverflow.com/users/234270/speedplane
        class ExitCodeProcess(ctypes.Structure):
            _fields_ = [('hProcess', ctypes.c_void_p),
                        ('lpExitCode', ctypes.POINTER(ctypes.c_ulong))]
        SYNCHRONIZE = 0x100000
        PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
        process = self._kernel32.OpenProcess(SYNCHRONIZE|PROCESS_QUERY_LIMITED_INFORMATION, 0, pid)
        if not process:
            return False
        ec = ExitCodeProcess()
        out = self._kernel32.GetExitCodeProcess(process, ctypes.byref(ec))
        if not out:
            err = self._kernel32.GetLastError()
            if self._kernel32.GetLastError() == 5:
                # Access is denied.
                logging.warning("Access is denied to get pid info.")
            self._kernel32.CloseHandle(process)
            return False
        elif bool(ec.lpExitCode):
            # There is an exit code, it quit
            self._kernel32.CloseHandle(process)
            return False
        # No exit code, it's running.
        self._kernel32.CloseHandle(process)
        return True 
Example #29
Source File: get_system_info.py    From py-cpuinfo with MIT License 5 votes vote down vote up
def free(self):
		import ctypes

		# Free the function memory segment
		if is_windows:
			MEM_RELEASE = ctypes.c_ulong(0x8000)
			ctypes.windll.kernel32.VirtualFree(ctypes.c_void_p(self.address), ctypes.c_size_t(0), MEM_RELEASE)
		else:
			self.mm.close()

		self.prochandle = None
		self.mm = None
		self.func = None
		self.address = None
		self.size = 0 
Example #30
Source File: __init__.py    From python-libxdo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def move_mouse_relative_to_window(self, window, x, y):
        """
        Move the mouse to a specific location relative to the top-left corner
        of a window.

        :param x: the target X coordinate on the screen in pixels.
        :param y: the target Y coordinate on the screen in pixels.
        """
        _libxdo.xdo_move_mouse_relative_to_window(
            self._xdo, ctypes.c_ulong(window), x, y)