Python ctypes.c_ulonglong() Examples

The following are 30 code examples of ctypes.c_ulonglong(). 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: __init__.py    From libnacl with Apache License 2.0 6 votes vote down vote up
def crypto_sign(msg, sk):
    '''
    Sign the given message with the given signing key
    '''
    if len(sk) != crypto_sign_SECRETKEYBYTES:
        raise ValueError('Invalid secret key')

    sig = ctypes.create_string_buffer(len(msg) + crypto_sign_BYTES)
    slen = ctypes.pointer(ctypes.c_ulonglong())
    ret = nacl.crypto_sign(
            sig,
            slen,
            msg,
            ctypes.c_ulonglong(len(msg)),
            sk)
    if ret:
        raise ValueError('Failed to sign message')
    return sig.raw 
Example #2
Source File: wnfcom.py    From wnfun with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def SetStateName(self, WnfName):
        tmpName = 0
        try:
            tmpName = g_WellKnownWnfNames[WnfName.upper()]
        except:
            if len(WnfName)>2 and WnfName[1] == 'x':
                WnfName = WnfName[2:]
            try:
                tmpName = int(WnfName, 16)
            except:
                tmpName = 0
                self.pprint("[Error] Could not validate the provided name")
                return False

        self.StateName = ctypes.c_longlong(tmpName)
        self.internalName.value = ctypes.c_ulonglong(tmpName ^ WNF_STATE_KEY)
        return True 
Example #3
Source File: jlink.py    From pylink with Apache License 2.0 6 votes vote down vote up
def memory_read64(self, addr, num_long_words):
        """Reads memory from the target system in units of 64-bits.

        Args:
          self (JLink): the ``JLink`` instance
          addr (int): start address to read from
          num_long_words (int): number of long words to read

        Returns:
          List of long words read from the target system.

        Raises:
          JLinkException: if memory could not be read
        """
        buf_size = num_long_words
        buf = (ctypes.c_ulonglong * buf_size)()
        units_read = self._dll.JLINKARM_ReadMemU64(addr, buf_size, buf, 0)
        if units_read < 0:
            raise errors.JLinkException(units_read)

        return buf[:units_read] 
Example #4
Source File: diskutils.py    From os-win with Apache License 2.0 6 votes vote down vote up
def get_disk_capacity(self, path, ignore_errors=False):
        """Returns total/free space for a given directory."""
        norm_path = os.path.abspath(path)

        total_bytes = ctypes.c_ulonglong(0)
        free_bytes = ctypes.c_ulonglong(0)

        try:
            self._win32_utils.run_and_check_output(
                kernel32.GetDiskFreeSpaceExW,
                ctypes.c_wchar_p(norm_path),
                None,
                ctypes.pointer(total_bytes),
                ctypes.pointer(free_bytes),
                kernel32_lib_func=True)
            return total_bytes.value, free_bytes.value
        except exceptions.Win32Exception as exc:
            LOG.error("Could not get disk %(path)s capacity info. "
                      "Exception: %(exc)s",
                      dict(path=path,
                           exc=exc))
            if ignore_errors:
                return 0, 0
            else:
                raise exc 
Example #5
Source File: test_clusapi_utils.py    From os-win with Apache License 2.0 6 votes vote down vote up
def _get_fake_prop_list(self):
        syntax = w_const.CLUSPROP_SYNTAX_LIST_VALUE_DWORD
        migr_type = wintypes.DWORD(self._LIVE_MIGRATION_TYPE)

        prop_entries = [
            self._clusapi_utils.get_property_list_entry(
                w_const.CLUS_RESTYPE_NAME_VM, syntax, migr_type),
            self._clusapi_utils.get_property_list_entry(
                w_const.CLUS_RESTYPE_NAME_VM_CONFIG, syntax, migr_type),
            self._clusapi_utils.get_property_list_entry(
                w_const.CLUSREG_NAME_GRP_STATUS_INFORMATION,
                w_const.CLUSPROP_SYNTAX_LIST_VALUE_ULARGE_INTEGER,
                ctypes.c_ulonglong(w_const.
                    CLUSGRP_STATUS_WAITING_IN_QUEUE_FOR_MOVE)),  # noqa
            self._clusapi_utils.get_property_list_entry(
                w_const.CLUSREG_NAME_GRP_TYPE,
                w_const.CLUSPROP_SYNTAX_LIST_VALUE_DWORD,
                ctypes.c_ulong(w_const.ClusGroupTypeVirtualMachine)),
        ]

        prop_list = self._clusapi_utils.get_property_list(prop_entries)
        return prop_list 
Example #6
Source File: __init__.py    From libnacl with Apache License 2.0 6 votes vote down vote up
def crypto_generichash(msg, key=None):
    '''
    Compute the blake2 hash of the given message with a given key
    '''
    hbuf = ctypes.create_string_buffer(crypto_generichash_BYTES)
    if key:
        key_len = len(key)
    else:
        key_len = 0
    nacl.crypto_generichash(
            hbuf,
            ctypes.c_size_t(len(hbuf)),
            msg,
            ctypes.c_ulonglong(len(msg)),
            key,
            ctypes.c_size_t(key_len))
    return hbuf.raw


# String cmp 
Example #7
Source File: hci.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def contract_ss(civec, norb, nelec):
    strs = civec._strs
    ndet = len(strs)
    ci1 = numpy.zeros_like(civec)

    strs = numpy.asarray(strs, order='C')
    civec = numpy.asarray(civec, order='C')
    ci1 = numpy.asarray(ci1, order='C')

    libhci.contract_ss_c(ctypes.c_int(norb), 
                        ctypes.c_int(nelec[0]), 
                        ctypes.c_int(nelec[1]), 
                        strs.ctypes.data_as(ctypes.c_void_p), 
                        civec.ctypes.data_as(ctypes.c_void_p), 
                        ctypes.c_ulonglong(ndet), 
                        ci1.ctypes.data_as(ctypes.c_void_p))

    return ci1 
Example #8
Source File: maintool.py    From plugin.program.indigo with GNU General Public License v3.0 6 votes vote down vote up
def get_free_space_mb(dirname):
    try:
        if xbmc.getCondVisibility('system.platform.windows'):
            import ctypes
            total_bytes = ctypes.c_int64()
            free_bytes = ctypes.c_ulonglong(0)
            ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(dirname), None, ctypes.pointer(total_bytes),
                                                       ctypes.pointer(free_bytes))
            if free_bytes.value != '0 MB Free':
                return free_bytes.value, total_bytes.value
        else:
            import subprocess
            df = subprocess.Popen(['df', dirname], stdout=subprocess.PIPE)
            output = df.communicate()[0].encode('utf-8').split('\n')[1].split()
            try:
                return int(output[3]) * 1024, int(output[1]) * 1024
            except Exception as e:
                kodi.log(str(e))
                return revert_size(output[3]), revert_size(output[1])
    except Exception as e:
        kodi.log(str(e))
        traceback.print_exc(file=sys.stdout)
    return get_kodi_size('System.FreeSpace'), get_kodi_size('System.TotalSpace') 
Example #9
Source File: __init__.py    From libnacl with Apache License 2.0 6 votes vote down vote up
def crypto_onetimeauth(message, key):
    """
    Constructs a one time authentication token for the given message using
    a given secret key

    Args:
        message (bytes): message to authenticate.
        key (bytes): secret key - must be of crypto_onetimeauth_KEYBYTES length.

    Returns:
        bytes: an authenticator, of crypto_onetimeauth_BYTES length.

    Raises:
        ValueError: if arguments' length is wrong.
    """
    if len(key) != crypto_onetimeauth_KEYBYTES:
        raise ValueError('Invalid secret key')

    tok = ctypes.create_string_buffer(crypto_onetimeauth_BYTES)
    # cannot fail
    _ = nacl.crypto_onetimeauth(
        tok, message, ctypes.c_ulonglong(len(message)), key)

    return tok.raw[:crypto_onetimeauth_BYTES] 
Example #10
Source File: nvml.py    From petridishnn with MIT License 6 votes vote down vote up
def memory(self):
        """Memory information in bytes

        Example:

            >>> print(ctx.device(0).memory())
            {'total': 4238016512L, 'used': 434831360L, 'free': 3803185152L}

        Returns:
            total/used/free memory in bytes
        """
        class GpuMemoryInfo(Structure):
            _fields_ = [
                ('total', c_ulonglong),
                ('free', c_ulonglong),
                ('used', c_ulonglong),
            ]

        c_memory = GpuMemoryInfo()
        _check_return(_NVML.get_function(
            "nvmlDeviceGetMemoryInfo")(self.hnd, byref(c_memory)))
        return {'total': c_memory.total, 'free': c_memory.free, 'used': c_memory.used} 
Example #11
Source File: win.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def get_physical_ram():
  """Returns the amount of installed RAM in Mb, rounded to the nearest number.
  """

  # https://msdn.microsoft.com/library/windows/desktop/aa366589.aspx
  class MemoryStatusEx(ctypes.Structure):
    _fields_ = [
        ('dwLength', ctypes.c_ulong),
        ('dwMemoryLoad', ctypes.c_ulong),
        ('dwTotalPhys', ctypes.c_ulonglong),
        ('dwAvailPhys', ctypes.c_ulonglong),
        ('dwTotalPageFile', ctypes.c_ulonglong),
        ('dwAvailPageFile', ctypes.c_ulonglong),
        ('dwTotalVirtual', ctypes.c_ulonglong),
        ('dwAvailVirtual', ctypes.c_ulonglong),
        ('dwAvailExtendedVirtual', ctypes.c_ulonglong),
    ]
  stat = MemoryStatusEx()
  stat.dwLength = ctypes.sizeof(MemoryStatusEx)  # pylint: disable=W0201
  ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat))
  return int(round(stat.dwTotalPhys / 1024. / 1024.)) 
Example #12
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 #13
Source File: __init__.py    From libnacl with Apache License 2.0 6 votes vote down vote up
def crypto_sign_verify_detached(sig, msg, vk):
    '''
    Verifies that sig is a valid signature for the message msg using the signer's verification key
    '''
    if len(sig) != crypto_sign_BYTES:
        raise ValueError('Invalid signature')
    if len(vk) != crypto_sign_PUBLICKEYBYTES:
        raise ValueError('Invalid public key')

    ret = nacl.crypto_sign_verify_detached(
            sig,
            msg,
            ctypes.c_ulonglong(len(msg)),
            vk)
    if ret:
        raise ValueError('Failed to validate message')
    return msg


# Authenticated Symmetric Encryption 
Example #14
Source File: __init__.py    From libnacl with Apache License 2.0 6 votes vote down vote up
def crypto_auth_verify(tok, msg, key):
    '''
    Verifies that the given authentication token is correct for the given
    message and key
    '''
    if len(key) != crypto_auth_KEYBYTES:
        raise ValueError('Invalid secret key')
    if len(tok) != crypto_auth_BYTES:
        raise ValueError('Invalid authenticator')

    ret = nacl.crypto_auth_verify(tok, msg, ctypes.c_ulonglong(len(msg)), key)
    if ret:
        raise ValueError('Failed to auth msg')
    return msg

# One time authentication 
Example #15
Source File: __init__.py    From libnacl with Apache License 2.0 6 votes vote down vote up
def crypto_box_seal_open(ctxt, pk, sk):
    '''
    Decrypts a message given the receiver's public and private key.
    '''
    if not HAS_SEAL:
        raise ValueError('Underlying Sodium library does not support sealed boxes')
    if len(pk) != crypto_box_PUBLICKEYBYTES:
        raise ValueError('Invalid public key')
    if len(sk) != crypto_box_SECRETKEYBYTES:
        raise ValueError('Invalid secret key')
    if not isinstance(ctxt, bytes):
        raise TypeError('Message must be bytes')

    c = ctypes.create_string_buffer(len(ctxt) - crypto_box_SEALBYTES)
    ret = nacl.crypto_box_seal_open(c, ctxt, ctypes.c_ulonglong(len(ctxt)), pk, sk)
    if ret:
        raise CryptError('Unable to decrypt message')
    return c.raw

# Signing functions 
Example #16
Source File: __init__.py    From libnacl with Apache License 2.0 6 votes vote down vote up
def crypto_box_seal(msg, pk):
    '''
    Using a public key to encrypt the given message. The identity of the sender cannot be verified.

    enc_msg = nacl.crypto_box_seal('secret message', <public key string>)
    '''
    if not HAS_SEAL:
        raise ValueError('Underlying Sodium library does not support sealed boxes')
    if len(pk) != crypto_box_PUBLICKEYBYTES:
        raise ValueError('Invalid public key')
    if not isinstance(msg, bytes):
        raise TypeError('Message must be bytes')

    c = ctypes.create_string_buffer(len(msg) + crypto_box_SEALBYTES)
    ret = nacl.crypto_box_seal(c, msg, ctypes.c_ulonglong(len(msg)), pk)
    if ret:
        raise CryptError('Unable to encrypt message')
    return c.raw 
Example #17
Source File: __init__.py    From libnacl with Apache License 2.0 6 votes vote down vote up
def crypto_box_open_easy_afternm(ctxt, nonce, k):
    '''
    Decrypts a ciphertext ctxt given k
    '''
    if len(k) != crypto_box_BEFORENMBYTES:
        raise ValueError('Invalid shared key')
    if len(nonce) != crypto_box_NONCEBYTES:
        raise ValueError('Invalid nonce')
    msg = ctypes.create_string_buffer(len(ctxt) - crypto_box_MACBYTES)
    ret = nacl.crypto_box_open_easy_afternm(
            msg,
            ctxt,
            ctypes.c_ulonglong(len(ctxt)),
            nonce,
            k)
    if ret:
        raise CryptError('unable to decrypt message')
    return msg.raw 
Example #18
Source File: __init__.py    From libnacl with Apache License 2.0 6 votes vote down vote up
def crypto_box_easy_afternm(msg, nonce, k):
    '''
    Using a precalculated shared key, encrypt the given message. A nonce
    must also be passed in, never reuse the nonce

    enc_msg = nacl.crypto_box_easy_afternm('secret message', <unique nonce>, <shared key string>)
    '''
    if len(k) != crypto_box_BEFORENMBYTES:
        raise ValueError('Invalid shared key')
    if len(nonce) != crypto_box_NONCEBYTES:
        raise ValueError('Invalid nonce')
    ctxt = ctypes.create_string_buffer(len(msg) + crypto_box_MACBYTES)
    ret = nacl.crypto_box_easy_afternm(ctxt, msg, ctypes.c_ulonglong(len(msg)), nonce, k)
    if ret:
        raise CryptError('Unable to encrypt messsage')
    return ctxt.raw 
Example #19
Source File: __init__.py    From libnacl with Apache License 2.0 6 votes vote down vote up
def crypto_sign_open(sig, vk):
    '''
    Verifies the signed message sig using the signer's verification key
    '''
    if len(vk) != crypto_sign_PUBLICKEYBYTES:
        raise ValueError('Invalid public key')

    msg = ctypes.create_string_buffer(len(sig))
    msglen = ctypes.c_ulonglong()
    msglenp = ctypes.pointer(msglen)
    ret = nacl.crypto_sign_open(
            msg,
            msglenp,
            sig,
            ctypes.c_ulonglong(len(sig)),
            vk)
    if ret:
        raise ValueError('Failed to validate message')
    return msg.raw[:msglen.value]  # pylint: disable=invalid-slice-index 
Example #20
Source File: __init__.py    From libnacl with Apache License 2.0 6 votes vote down vote up
def crypto_box_open_easy(ctxt, nonce, pk, sk):
    '''
    Decrypts a message given the receiver's private key, and sender's public key
    '''
    if len(pk) != crypto_box_PUBLICKEYBYTES:
        raise ValueError('Invalid public key')
    if len(sk) != crypto_box_SECRETKEYBYTES:
        raise ValueError('Invalid secret key')
    if len(nonce) != crypto_box_NONCEBYTES:
        raise ValueError('Invalid nonce')
    msg = ctypes.create_string_buffer(len(ctxt) - crypto_box_MACBYTES)
    ret = nacl.crypto_box_open(
            msg,
            ctxt,
            ctypes.c_ulonglong(len(ctxt)),
            nonce,
            pk,
            sk)
    if ret:
        raise CryptError('Unable to decrypt ciphertext')
    return msg.raw[crypto_box_ZEROBYTES:] 
Example #21
Source File: __init__.py    From libnacl with Apache License 2.0 6 votes vote down vote up
def crypto_box_easy(msg, nonce, pk, sk):
    '''
    Using a public key and a secret key encrypt the given message. A nonce
    must also be passed in, never reuse the nonce

    enc_msg = nacl.crypto_box_easy('secret message', <unique nonce>, <public key string>, <secret key string>)
    '''
    if len(pk) != crypto_box_PUBLICKEYBYTES:
        raise ValueError('Invalid public key')
    if len(sk) != crypto_box_SECRETKEYBYTES:
        raise ValueError('Invalid secret key')
    if len(nonce) != crypto_box_NONCEBYTES:
        raise ValueError('Invalid nonce')
    c = ctypes.create_string_buffer(len(msg) + crypto_box_MACBYTES)
    ret = nacl.crypto_box(c, msg, ctypes.c_ulonglong(len(msg)), nonce, pk, sk)
    if ret:
        raise CryptError('Unable to encrypt message')
    return c.raw 
Example #22
Source File: __init__.py    From libnacl with Apache License 2.0 6 votes vote down vote up
def crypto_box_open(ctxt, nonce, pk, sk):
    '''
    Decrypts a message given the receiver's private key, and sender's public key
    '''
    if len(pk) != crypto_box_PUBLICKEYBYTES:
        raise ValueError('Invalid public key')
    if len(sk) != crypto_box_SECRETKEYBYTES:
        raise ValueError('Invalid secret key')
    if len(nonce) != crypto_box_NONCEBYTES:
        raise ValueError('Invalid nonce')
    pad = b'\x00' * crypto_box_BOXZEROBYTES + ctxt
    msg = ctypes.create_string_buffer(len(pad))
    ret = nacl.crypto_box_open(
            msg,
            pad,
            ctypes.c_ulonglong(len(pad)),
            nonce,
            pk,
            sk)
    if ret:
        raise CryptError('Unable to decrypt ciphertext')
    return msg.raw[crypto_box_ZEROBYTES:] 
Example #23
Source File: __init__.py    From libnacl with Apache License 2.0 6 votes vote down vote up
def crypto_box(msg, nonce, pk, sk):
    '''
    Using a public key and a secret key encrypt the given message. A nonce
    must also be passed in, never reuse the nonce

    enc_msg = nacl.crypto_box('secret message', <unique nonce>, <public key string>, <secret key string>)
    '''
    if len(pk) != crypto_box_PUBLICKEYBYTES:
        raise ValueError('Invalid public key')
    if len(sk) != crypto_box_SECRETKEYBYTES:
        raise ValueError('Invalid secret key')
    if len(nonce) != crypto_box_NONCEBYTES:
        raise ValueError('Invalid nonce')
    pad = b'\x00' * crypto_box_ZEROBYTES + msg
    c = ctypes.create_string_buffer(len(pad))
    ret = nacl.crypto_box(c, pad, ctypes.c_ulonglong(len(pad)), nonce, pk, sk)
    if ret:
        raise CryptError('Unable to encrypt message')
    return c.raw[crypto_box_BOXZEROBYTES:] 
Example #24
Source File: __init__.py    From libnacl with Apache License 2.0 6 votes vote down vote up
def crypto_secretbox_open(ctxt, nonce, key):
    """
    Decrypts a ciphertext ctxt given the receivers private key, and senders
    public key
    """
    if len(key) != crypto_secretbox_KEYBYTES:
        raise ValueError('Invalid key')

    if len(nonce) != crypto_secretbox_NONCEBYTES:
        raise ValueError('Invalid nonce')

    pad = b'\x00' * crypto_secretbox_BOXZEROBYTES + ctxt
    msg = ctypes.create_string_buffer(len(pad))
    ret = nacl.crypto_secretbox_open(
            msg,
            pad,
            ctypes.c_ulonglong(len(pad)),
            nonce,
            key)
    if ret:
        raise ValueError('Failed to decrypt message')
    return msg.raw[crypto_secretbox_ZEROBYTES:]

# Authenticated Symmetric Encryption improved version 
Example #25
Source File: __init__.py    From libnacl with Apache License 2.0 5 votes vote down vote up
def crypto_aead_aes256gcm_encrypt(message, aad, nonce, key):
    """Encrypts and authenticates a message with public additional data using the given secret key, and nonce

    Args:
        message (bytes): a message to encrypt
        aad  (bytes): additional public data to authenticate
        nonce (bytes): nonce, does not have to be confidential must be
            `crypto_aead_aes256gcm_NPUBBYTES` in length
        key (bytes): secret key, must be `crypto_aead_aes256gcm_KEYBYTES` in
            length

    Returns:
        bytes: the ciphertext

    Raises:
        ValueError: if arguments' length is wrong or the operation has failed.
    """
    if not HAS_AEAD_AES256GCM:
        raise ValueError('Underlying Sodium library does not support AES256-GCM AEAD')

    if len(key) != crypto_aead_aes256gcm_KEYBYTES:
        raise ValueError('Invalid key')

    if len(nonce) != crypto_aead_aes256gcm_NPUBBYTES:
        raise ValueError('Invalid nonce')

    length = len(message) + crypto_aead_aes256gcm_ABYTES
    clen = ctypes.c_ulonglong()
    c = ctypes.create_string_buffer(length)
    ret = nacl.crypto_aead_aes256gcm_encrypt(
        c, ctypes.pointer(clen),
        message, ctypes.c_ulonglong(len(message)),
        aad, ctypes.c_ulonglong(len(aad)),
        None,
        nonce, key)
    if ret:
        raise ValueError('Failed to encrypt message')
    return c.raw 
Example #26
Source File: ewf.py    From volatility with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, volumes):
        if isinstance(volumes, str):
            volumes = [volumes, ]

        volume_array = c_char_p * len(volumes)
        self.handle = libewf.libewf_open(volume_array(*volumes), c_int(len(volumes)),
                                         c_int(1))
        if self.handle == 0:
            raise RuntimeError("Unable to open ewf file")

        self.readptr = 0
        size_p = pointer(c_ulonglong(0))
        libewf.libewf_get_media_size(self.handle, size_p)
        self.size = size_p.contents.value 
Example #27
Source File: __init__.py    From libnacl with Apache License 2.0 5 votes vote down vote up
def crypto_secretbox(message, nonce, key):
    """Encrypts and authenticates a message using the given secret key, and nonce

    Args:
        message (bytes): a message to encrypt
        nonce (bytes): nonce, does not have to be confidential must be
            `crypto_secretbox_NONCEBYTES` in length
        key (bytes): secret key, must be `crypto_secretbox_KEYBYTES` in
            length

    Returns:
        bytes: the ciphertext

    Raises:
        ValueError: if arguments' length is wrong or the operation has failed.
    """
    if len(key) != crypto_secretbox_KEYBYTES:
        raise ValueError('Invalid key')

    if len(nonce) != crypto_secretbox_NONCEBYTES:
        raise ValueError('Invalid nonce')

    pad = b'\x00' * crypto_secretbox_ZEROBYTES + message
    ctxt = ctypes.create_string_buffer(len(pad))
    ret = nacl.crypto_secretbox(
        ctxt, pad, ctypes.c_ulonglong(len(pad)), nonce, key)
    if ret:
        raise ValueError('Failed to encrypt message')
    return ctxt.raw[crypto_secretbox_BOXZEROBYTES:] 
Example #28
Source File: ewf.py    From volatility with GNU General Public License v2.0 5 votes vote down vote up
def read(self, length):
        buf = create_string_buffer(length)
        length = libewf.libewf_read_random(self.handle, buf,
                                           c_ulong(length),
                                           c_ulonglong(self.readptr))

        return buf.raw[:length] 
Example #29
Source File: core.py    From pyrealsense with Apache License 2.0 5 votes vote down vote up
def get_frame_number(self, stream):
        """Retrieve the frame number for specific stream.

        Args:
            stream (int): value from :class:`pyrealsense.constants.rs_stream`.

        Returns:
            (double): frame number.
        """
        lrs.rs_get_frame_number.restype = ctypes.c_ulonglong
        e = ctypes.POINTER(rs_error)()
        return lrs.rs_get_frame_number(self.dev, stream, ctypes.byref(e)) 
Example #30
Source File: test_iscsi_utils.py    From os-win with Apache License 2.0 5 votes vote down vote up
def test_login_iscsi_target(self, mock_cls_ISCSI_UNIQUE_SESSION_ID,
                                mock_cls_ISCSI_UNIQUE_CONNECTION_ID,
                                mock_byref):
        fake_target_name = 'fake_target_name'

        resulted_session_id, resulted_conection_id = (
            self._initiator._login_iscsi_target(fake_target_name))

        args_list = self._mock_run.call_args_list[0][0]

        self.assertIsInstance(args_list[1], ctypes.c_wchar_p)
        self.assertEqual(fake_target_name, args_list[1].value)
        self.assertIsInstance(args_list[4], ctypes.c_ulong)
        self.assertEqual(
            ctypes.c_ulong(w_const.ISCSI_ANY_INITIATOR_PORT).value,
            args_list[4].value)
        self.assertIsInstance(args_list[6], ctypes.c_ulonglong)
        self.assertEqual(0, args_list[6].value)
        self.assertIsInstance(args_list[9], ctypes.c_ulong)
        self.assertEqual(0, args_list[9].value)

        mock_byref.assert_has_calls([
            mock.call(mock_cls_ISCSI_UNIQUE_SESSION_ID.return_value),
            mock.call(mock_cls_ISCSI_UNIQUE_CONNECTION_ID.return_value)])
        self.assertEqual(
            mock_cls_ISCSI_UNIQUE_SESSION_ID.return_value,
            resulted_session_id)
        self.assertEqual(
            mock_cls_ISCSI_UNIQUE_CONNECTION_ID.return_value,
            resulted_conection_id)