Python ctypes.c_wchar_p() Examples

The following are 30 code examples of ctypes.c_wchar_p(). 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: ae.py    From Splunk-Assessment-of-Mitigation-Implementations with The Unlicense 7 votes vote down vote up
def checkFirmwareType(self):
        # Load in kernel32.dll
        kernel32_dll = ctypes.WinDLL("C:\\Windows\\System32\\kernel32.dll")

        # Because we're using bogus parameters in the function call, it
        # should always fail (return 0).
        if kernel32_dll.GetFirmwareEnvironmentVariableW(ctypes.c_wchar_p(""),
            ctypes.c_wchar_p("{00000000-0000-0000-0000-000000000000}"), None,
            ctypes.c_int(0)) == 0:
            # Check the last error returned to determine firmware type.
            # If the error is anything other than ERROR_INVALID_FUNCTION
            # or ERROR_NOACCESS, raise an exception.
            last_error = ctypes.GetLastError()
            if last_error == self._ERROR_INVALID_FUNCTION:
                return "Legacy"
            elif last_error == self._ERROR_NOACCESS:
                return "UEFI"
            else:
                raise ctypes.WinError()
        else:
            return "Unknown"

    # Check for PAE, SMEP, SMAP, and NX hardware support using CPUID. 
Example #2
Source File: pyperclip.py    From GDMC with ISC License 6 votes vote down vote up
def _copyCygwin(text):
    GMEM_DDESHARE = 0x2000
    CF_UNICODETEXT = 13
    d = ctypes.cdll
    try:  # Python 2
        if not isinstance(text, unicode):
            text = text.decode('mbcs')
    except NameError:
        if not isinstance(text, str):
            text = text.decode('mbcs')
    d.user32.OpenClipboard(None)
    d.user32.EmptyClipboard()
    hCd = d.kernel32.GlobalAlloc(GMEM_DDESHARE, len(text.encode('utf-16-le')) + 2)
    pchData = d.kernel32.GlobalLock(hCd)
    ctypes.cdll.msvcrt.wcscpy(ctypes.c_wchar_p(pchData), text)
    d.kernel32.GlobalUnlock(hCd)
    d.user32.SetClipboardData(CF_UNICODETEXT, hCd)
    d.user32.CloseClipboard() 
Example #3
Source File: link.py    From core with MIT License 6 votes vote down vote up
def _create_windows(source, destination, link_type):
    """Creates hardlink at destination from source in Windows."""

    if link_type == HARDLINK:
        import ctypes
        from ctypes.wintypes import BOOL
        CreateHardLink = ctypes.windll.kernel32.CreateHardLinkW
        CreateHardLink.argtypes = [
            ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_void_p
        ]
        CreateHardLink.restype = BOOL

        res = CreateHardLink(destination, source, None)
        if res == 0:
            raise ctypes.WinError()
    else:
        raise NotImplementedError("Link type unrecognized.") 
Example #4
Source File: wrapper.py    From sqrmelon with MIT License 6 votes vote down vote up
def __init__(self, *args):
        assert self.__class__ != VectorBase, 'Instantiation of abstract class.'

        self._data = None
        if args:
            if isinstance(args[0], (long, ctypes.c_voidp, ctypes.c_void_p, ctypes.c_char_p, ctypes.c_wchar_p, ctypes.c_long)):
                self._ptr = args[0]
            elif isinstance(args[0], self.__class__):
                self._ptr = _dllHandle.Vector_Copy(args[0]._ptr)
            else:
                assert len(
                    args) == self.__class__._size and self.__class__._size <= 4, 'Attempting to constructor vector of size {} with either wrong number of arguments {} or beyond maximum size 4.'.format(
                    self.__class__._size, args)
                data = (ctypes.c_float * 4)(*(list(args) + [0] * (4 - self.__class__._size)))
                self._ptr = _dllHandle.Vector_FromFloat4(data)
        else:
            self._ptr = _dllHandle.Vector_Vector() 
Example #5
Source File: pyperclip.py    From GDMC with ISC License 6 votes vote down vote up
def _copyWindows(text):
    GMEM_DDESHARE = 0x2000
    CF_UNICODETEXT = 13
    d = ctypes.windll # cdll expects 4 more bytes in user32.OpenClipboard(None)
    try:  # Python 2
        if not isinstance(text, unicode):
            text = text.decode('mbcs')
    except NameError:
        if not isinstance(text, str):
            text = text.decode('mbcs')
    d.user32.OpenClipboard(None)
    d.user32.EmptyClipboard()
    hCd = d.kernel32.GlobalAlloc(GMEM_DDESHARE, len(text.encode('utf-16-le')) + 2)
    pchData = d.kernel32.GlobalLock(hCd)
    ctypes.cdll.msvcrt.wcscpy(ctypes.c_wchar_p(pchData), text)
    d.kernel32.GlobalUnlock(hCd)
    d.user32.SetClipboardData(CF_UNICODETEXT, hCd)
    d.user32.CloseClipboard() 
Example #6
Source File: path.py    From Computable with MIT License 6 votes vote down vote up
def _get_long_path_name(path):
        """Get a long path name (expand ~) on Windows using ctypes.

        Examples
        --------

        >>> get_long_path_name('c:\\docume~1')
        u'c:\\\\Documents and Settings'

        """
        try:
            import ctypes
        except ImportError:
            raise ImportError('you need to have ctypes installed for this to work')
        _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
        _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p,
            ctypes.c_uint ]

        buf = ctypes.create_unicode_buffer(260)
        rv = _GetLongPathName(path, buf, 260)
        if rv == 0 or rv > 260:
            return path
        else:
            return buf.value 
Example #7
Source File: file_path.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def get_free_space(path):
  """Returns the number of free bytes.

  On POSIX platforms, this returns the free space as visible by the current
  user. On some systems, there's a percentage of the free space on the partition
  that is only accessible as the root user.
  """
  if sys.platform == 'win32':
    free_bytes = ctypes.c_ulonglong(0)
    windll.kernel32.GetDiskFreeSpaceExW(
        ctypes.c_wchar_p(path), None, None, ctypes.pointer(free_bytes))
    return free_bytes.value
  # For OSes other than Windows.
  f = fs.statvfs(path)  # pylint: disable=E1101
  return f.f_bfree * f.f_frsize


### Write file functions. 
Example #8
Source File: win.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def _get_window_class(hwnd):
  """Returns the class name of |hwnd|."""
  ctypes.windll.user32.GetClassNameW.restype = ctypes.c_int
  ctypes.windll.user32.GetClassNameW.argtypes = [
      ctypes.c_void_p,  # HWND
      ctypes.c_wchar_p,
      ctypes.c_int
  ]
  name = ctypes.create_unicode_buffer(257)
  name_len = ctypes.windll.user32.GetClassNameW(hwnd, name, len(name))
  if name_len <= 0 or name_len >= len(name):
    raise ctypes.WinError(descr='GetClassNameW failed; %s' %
                          ctypes.FormatError())
  return name.value


## Public API. 
Example #9
Source File: installer.py    From JavaScript-Completions with MIT License 6 votes vote down vote up
def rmtree(self, path) :
    if node_variables.NODE_JS_OS == "win" :
      import string
      from ctypes import windll, c_int, c_wchar_p
      UNUSUED_DRIVE_LETTER = ""
      for letter in string.ascii_uppercase:
        if not os.path.exists(letter+":") :
          UNUSUED_DRIVE_LETTER = letter+":"
          break
      if not UNUSUED_DRIVE_LETTER :
        sublime.message_dialog("Can't remove node.js! UNUSUED_DRIVE_LETTER not found.")
        return
      DefineDosDevice = windll.kernel32.DefineDosDeviceW
      DefineDosDevice.argtypes = [ c_int, c_wchar_p, c_wchar_p ]
      DefineDosDevice(0, UNUSUED_DRIVE_LETTER, path)
      try:
        shutil.rmtree(UNUSUED_DRIVE_LETTER)
      except Exception as e:
        print("Error: "+traceback.format_exc())
      finally:
        DefineDosDevice(2, UNUSUED_DRIVE_LETTER, path)  
    else :
      shutil.rmtree(path) 
Example #10
Source File: disk.py    From cloudbase-init with Apache License 2.0 6 votes vote down vote up
def open(self):
        access = self.GENERIC_READ
        share_mode = self.FILE_SHARE_READ
        if self._allow_write:
            access |= self.GENERIC_WRITE
            share_mode |= self.FILE_SHARE_WRITE
            attributes = 0
        else:
            attributes = self.FILE_ATTRIBUTE_READONLY

        handle = kernel32.CreateFileW(
            ctypes.c_wchar_p(self._path),
            access,
            share_mode,
            0,
            self.OPEN_EXISTING,
            attributes,
            0)
        if handle == self.INVALID_HANDLE_VALUE:
            raise exception.WindowsCloudbaseInitException(
                'Cannot open file: %r')
        self._handle = handle
        self._sector_size, self._disk_size, self.fixed =\
            self._get_geometry() 
Example #11
Source File: tools.py    From mysql-utilities with GNU General Public License v2.0 5 votes vote down vote up
def estimate_free_space(path, unit_multiple=2):
    """Estimated free space for the given path.

    Calculates free space for the given path, returning the value
    on the size given by the unit_multiple.

    path[in]             the path to calculate the free space for.
    unit_multiple[in]    the unit size given as a multiple.
                         Accepts int values > to zero.
                         Size    unit_multiple
                          bytes        0
                          Kilobytes    1
                          Megabytes    2
                          Gigabytes    3
                         and so on...

    Returns folder/drive free space (in bytes)
    """
    unit_size = 1024 ** unit_multiple
    if os.name == 'nt':
        free_bytes = ctypes.c_ulonglong(0)
        ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(path),
                                                   None, None,
                                                   ctypes.pointer(free_bytes))
        return free_bytes.value / unit_size
    else:
        st = os.statvfs(path)  # pylint: disable=E1101
        return st.f_bavail * st.f_frsize / unit_size 
Example #12
Source File: logi_led.py    From logiPy with MIT License 5 votes vote down vote up
def logi_led_set_config_option_label(key, label):
    """ set the label for a key.

        for example, label 'health/pulse_on_low' as 'Health - Pulse on Low':
         logi_led_set_config_option_label('health', 'Health')
         logi_led_set_config_option_label('health/pulse_on_low', 'Pulse on Low') """
    if led_dll:
        key   = ctypes.c_wchar_p(key)
        label = ctypes.c_wchar_p(label)
        return bool(led_dll.LogiSetConfigOptionLabel(key, label, _LOGI_SHARED_SDK_LED))
    else:
        return False 
Example #13
Source File: analyzer.py    From CuckooSploit with GNU General Public License v3.0 5 votes vote down vote up
def dump_file(file_path):
    """Create a copy of the given file path."""
    try:
        if os.path.exists(file_path):
            sha256 = hash_file(hashlib.sha256, file_path)
            if sha256 in DUMPED_LIST:
                # The file was already dumped, just skip.
                return
        else:
            log.warning("File at path \"%s\" does not exist, skip.",
                        file_path)
            return
    except IOError as e:
        log.warning("Unable to access file at path \"%s\": %s", file_path, e)
        return

    # 32k is the maximum length for a filename
    path = create_unicode_buffer(32 * 1024)
    name = c_wchar_p()
    KERNEL32.GetFullPathNameW(unicode(file_path), 32 * 1024, path, byref(name))
    file_path = path.value

    # Check if the path has a valid file name, otherwise it's a directory
    # and we should abort the dump.
    if name.value:
        # Should be able to extract Alternate Data Streams names too.
        file_name = name.value[name.value.find(":")+1:]
    else:
        return

    upload_path = os.path.join("files",
                               str(random.randint(100000000, 9999999999)),
                               file_name)
    try:
        upload_to_host(file_path, upload_path)
        DUMPED_LIST.append(sha256)
    except (IOError, socket.error) as e:
        log.error("Unable to upload dropped file at path \"%s\": %s",
                  file_path, e) 
Example #14
Source File: logi_led.py    From logiPy with MIT License 5 votes vote down vote up
def logi_led_get_config_option_color(key, *args):
    """ get the default value for the key as a color. if the call fails, the return value is None.
         note this function can either be called with red_percentage, green_percentage, and blue_percentage or with the logi_led Color object.

        for example, get the low health color:
         logi_led_get_config_option_color('health/pulse_color', 100, 0, 0)
         logi_led_get_config_option_color('health/pulse_color', Color('red'))
         logi_led_get_config_option_color('health/pulse_color', Color('#ff0000'))
         logi_led_get_config_option_color('health/pulse_color', Color(255, 0, 0)) """
    if led_dll:
        key              = ctypes.c_wchar_p(key)
        default          = None
        red_percentage   = 0
        green_percentage = 0
        blue_percentage  = 0
        if isinstance(args[0], Color):
            default = args[0]
        else:
            red_percentage   = args[0]
            green_percentage = args[1]
            blue_percentage  = args[2]
        if default:
            red   = ctypes.c_int(default.red)
            green = ctypes.c_int(default.green)
            blue  = ctypes.c_int(default.blue)
        else:
            red   = ctypes.c_int(int((red_percentage / 100.0) * 255))
            green = ctypes.c_int(int((green_percentage / 100.0) * 255))
            blue  = ctypes.c_int(int((blue_percentage / 100.0) * 255))
        if led_dll.LogiGetConfigOptionColor(key, ctypes.pointer(red), ctypes.pointer(green), ctypes.pointer(blue), _LOGI_SHARED_SDK_LED):
            return Color(red.value, green.value, blue.value)
    return None 
Example #15
Source File: win.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def _get_mount_points():
  """Returns the list of 'fixed' drives in format 'X:\\'."""
  ctypes.windll.kernel32.GetDriveTypeW.argtypes = (ctypes.c_wchar_p,)
  ctypes.windll.kernel32.GetDriveTypeW.restype = ctypes.c_ulong
  DRIVE_FIXED = 3
  # https://msdn.microsoft.com/library/windows/desktop/aa364939.aspx
  return [
      u'%s:\\' % letter
      for letter in string.lowercase
      if ctypes.windll.kernel32.GetDriveTypeW(letter + ':\\') == DRIVE_FIXED
  ] 
Example #16
Source File: win.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def _get_disk_info(mount_point):
  """Returns total and free space on a mount point in Mb."""
  total_bytes = ctypes.c_ulonglong(0)
  free_bytes = ctypes.c_ulonglong(0)
  ctypes.windll.kernel32.GetDiskFreeSpaceExW(
      ctypes.c_wchar_p(mount_point), None, ctypes.pointer(total_bytes),
      ctypes.pointer(free_bytes))
  return {
    u'free_mb': round(free_bytes.value / 1024. / 1024., 1),
    u'size_mb': round(total_bytes.value / 1024. / 1024., 1),
  } 
Example #17
Source File: breakpoint.py    From OpenXMolar with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _cast_signature_pointers_to_void(self, signature):
        c_void_p  = ctypes.c_void_p
        c_char_p  = ctypes.c_char_p
        c_wchar_p = ctypes.c_wchar_p
        _Pointer  = ctypes._Pointer
        cast      = ctypes.cast
        for i in xrange(len(signature)):
            t = signature[i]
            if t is not c_void_p and (issubclass(t, _Pointer) \
                                            or t in [c_char_p, c_wchar_p]):
                signature[i] = cast(t, c_void_p) 
Example #18
Source File: main.py    From plugin.video.iptv.recorder with GNU General Public License v3.0 5 votes vote down vote up
def get_free_space_mb(dirname):
    """Return folder/drive free space (in megabytes)."""
    if platform.system() == 'Windows':
        free_bytes = ctypes.c_ulonglong(0)
        ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(dirname), None, None, ctypes.pointer(free_bytes))
        return free_bytes.value / 1024 / 1024
    else:
        try:
            st = os.statvfs(dirname)
            return st.f_bavail * st.f_frsize / 1024 / 1024
        except:
            #log(dirname)
            return 
Example #19
Source File: logi_led.py    From logiPy with MIT License 5 votes vote down vote up
def logi_led_get_config_option_key_input(key, default=''):
    """ get the default value for the key as a key input. if the call fails, the return value is None.

        for example, get the primary ability key input:
         logi_led_get_config_option_key_input('abilities/primary', 'A') """
    if led_dll:
        key               = ctypes.c_wchar_p(key)
        default_key       = ctypes.create_string_buffer(256)
        default_key.value = default
        if led_dll.LogiGetConfigOptionKeyInput(key, default_key, _LOGI_SHARED_SDK_LED):
            return str(default_key.value)
    return None 
Example #20
Source File: pyperclip.py    From GDMC with ISC License 5 votes vote down vote up
def _pasteWindows():
    CF_UNICODETEXT = 13
    d = ctypes.windll
    d.user32.OpenClipboard(None)
    handle = d.user32.GetClipboardData(CF_UNICODETEXT)
    data = ctypes.c_wchar_p(handle).value
    d.user32.CloseClipboard()
    return data 
Example #21
Source File: logi_led.py    From logiPy with MIT License 5 votes vote down vote up
def logi_led_get_config_option_number(key, default=0):
    """ get the default value for the key as a number. if the call fails, the return value is None.

         for example, get the low health threshold:
          logi_led_get_config_option_number('health/low_health_threshold', 20.0) """
    if led_dll:
        key     = ctypes.c_wchar_p(key)
        default = ctypes.c_double(default)
        if led_dll.LogiGetConfigOptionNumber(key, ctypes.pointer(default), _LOGI_SHARED_SDK_LED):
            return default.value
    return None 
Example #22
Source File: logi_arx.py    From logiPy with MIT License 5 votes vote down vote up
def logi_arx_set_tags_content_by_class(tag_class, new_content):
    """ change at runtime the content (innerHTML) of a tag with the class tag_class from the old content to the new_content. """
    if arx_dll:
        tag_class   = ctypes.c_wchar_p(tag_class)
        new_content = ctypes.c_wchar_p(new_content)
        return bool(arx_dll.LogiArxSetTagsPropertyByClass(tag_class, new_content))
    else:
        return False 
Example #23
Source File: logi_arx.py    From logiPy with MIT License 5 votes vote down vote up
def logi_arx_set_tag_content_by_id(tag_id, new_content):
    """ change at runtime the content (innerHTML) of a tag with the id tag_id from the old content to the new_content. """
    if arx_dll:
        tag_id      = ctypes.c_wchar_p(tag_id)
        new_content = ctypes.c_wchar_p(new_content)
        return bool(arx_dll.LogiArxSetTagContentById(tag_id, new_content))
    else:
        return False 
Example #24
Source File: logi_arx.py    From logiPy with MIT License 5 votes vote down vote up
def logi_arx_set_tags_property_by_class(tag_class, prop, new_value):
    """ change at runtime a prop (property) on the tag with the class tag_class from the old value to the new_value. """
    if arx_dll:
        tag_class = ctypes.c_wchar_p(tag_class)
        prop      = ctypes.c_wchar_p(prop)
        new_value = ctypes.c_wchar_p(new_value)
        return bool(arx_dll.LogiArxSetTagsPropertyByClass(tag_class, prop, new_value))
    else:
        return False 
Example #25
Source File: logi_arx.py    From logiPy with MIT License 5 votes vote down vote up
def logi_arx_set_tag_property_by_id(tag_id, prop, new_value):
    """ change at runtime a prop (property) on the tag with the id tag_id from the old value to the new_value. """
    if arx_dll:
        tag_id    = ctypes.c_wchar_p(tag_id)
        prop      = ctypes.c_wchar_p(prop)
        new_value = ctypes.c_wchar_p(new_value)
        return bool(arx_dll.LogiArxSetTagPropertyById(tag_id, prop, new_value))
    else:
        return False 
Example #26
Source File: logi_arx.py    From logiPy with MIT License 5 votes vote down vote up
def logi_arx_add_image_from_bitmap(bitmap, width, height, file_name):
    """ compresses the image specified by the BGRA byte array bitmap (interpretting the array using width and height) into a png file with the name specified by file_name,
    then sends it over to the the device. note that the color bit order is BGRA rather than standard RGBA bit order. """
    if arx_dll:
        bitmap    = ctypes.c_char_p(bitmap)
        width     = ctypes.c_int(width)
        height    = ctypes.c_int(height)
        file_name = ctypes.c_wchar_p(file_name)
        return bool(arx_dll.LogiArxAddImageFromBitmap(bitmap, width, height, file_name))
    else:
        return False 
Example #27
Source File: logi_arx.py    From logiPy with MIT License 5 votes vote down vote up
def logi_arx_add_utf8_string_as(string_content, file_name, mime_type = None):
    """ sends a UTF8 string to the device and saves it to a virtual file called file_name. mime_type, if assigned, specifies the MIME type of the file. """
    if arx_dll:
        string_content = ctypes.c_wchar_p(string_content)
        file_name      = ctypes.c_wchar_p(file_name)
        mime_type      = ctypes.c_wchar_p(mime_type) if mime_type else ctypes.c_wchar_p('')
        return bool(arx_dll.LogiArxAddUTF8StringAs(string_content, file_name, mime_type))
    else:
        return False 
Example #28
Source File: logi_arx.py    From logiPy with MIT License 5 votes vote down vote up
def logi_arx_add_content_as(content, size, file_name, mime_type = None):
    """ sends content to the device and saves it to a virtual file called file_name. mime_type, if assigned, specifies the MIME type of the file. """
    if arx_dll:
        content   = ctypes.c_void_p(content)
        size      = ctypes.c_int(size)
        file_name = ctypes.c_wchar_p(file_name)
        mime_type = ctypes.c_wchar_p(mime_type) if mime_type else ctypes.c_wchar_p('')
        return bool(arx_dll.LogiArxAddContentAs(content, size, file_name, mime_type))
    else:
        return False 
Example #29
Source File: logi_arx.py    From logiPy with MIT License 5 votes vote down vote up
def logi_arx_add_file_as(file_path, file_name, mime_type = None):
    """ sends a file to the device from local a file_path and assigns a file_name to it. mime_type, if assigned, specifies the MIME type of the file. """
    if arx_dll:
        file_path = ctypes.c_wchar_p(file_path)
        file_name = ctypes.c_wchar_p(file_name)
        mime_type = ctypes.c_wchar_p(mime_type) if mime_type else ctypes.c_wchar_p('')
        return bool(arx_dll.LogiArxAddFileAs(file_path, file_name, mime_type))
    else:
        return False 
Example #30
Source File: logi_arx.py    From logiPy with MIT License 5 votes vote down vote up
def logi_arx_init(identifier, friendly_name, py_callback_function = None):
    """ initializes the applet on the app with the given friendly_name. """
    if arx_dll:
        global on_callback
        global callback_ref
        on_callback   = py_callback_function if py_callback_function else default_callback
        callback_ref  = ctypes.byref(CALLBACK_DEFINITION(callback_wrapper))
        identifier    = ctypes.c_wchar_p(identifier)
        friendly_name = ctypes.c_wchar_p(friendly_name)
        return bool(arx_dll.LogiArxInit(identifier, friendly_name, callback_ref))
    else:
        return False