Python ctypes.pointer() Examples

The following are 30 code examples of ctypes.pointer(). 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: com.py    From cWMI with Apache License 2.0 9 votes vote down vote up
def QueryInterface(self, riid):
        prototype = ctypes.WINFUNCTYPE(HRESULT,
                                       ctypes.POINTER(winapi.GUID),
                                       ctypes.POINTER(wintypes.LPVOID))

        paramflags = ((_In_, 'riid'),
                      (_Out_, 'ppvObject', ctypes.pointer(wintypes.LPVOID(None)))
                      )

        _QueryInterface = prototype(IUnknown_QueryInterface_Idx,
                                    'QueryInterface',
                                    paramflags)
        _QueryInterface.errcheck = winapi.RAISE_NON_ZERO_ERR
        return_ptr = _QueryInterface(self.this,
                                     ctypes.byref(riid))
        return IUnknown(return_ptr.contents) 
Example #2
Source File: smbus.py    From Adafruit_Python_PureIO with MIT License 7 votes vote down vote up
def read_byte_data(self, addr, cmd):
        """Read a single byte from the specified cmd register of the device."""
        assert (
            self._device is not None
        ), "Bus must be opened before operations are made against it!"
        # Build ctypes values to marshall between ioctl and Python.
        reg = c_uint8(cmd)
        result = c_uint8()
        # Build ioctl request.
        request = make_i2c_rdwr_data(
            [
                (addr, 0, 1, pointer(reg)),  # Write cmd register.
                (addr, I2C_M_RD, 1, pointer(result)),  # Read 1 byte as result.
            ]
        )
        # Make ioctl call and return result data.
        ioctl(self._device.fileno(), I2C_RDWR, request)
        return result.value 
Example #3
Source File: ndarray.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def to_dlpack_for_write(self):
        """Returns a reference view of NDArray that represents as DLManagedTensor until
        all previous read/write operations on the current array are finished.

        Returns
        -------
        PyCapsule (the pointer of DLManagedTensor)
            a reference view of NDArray that represents as DLManagedTensor.

        Examples
        --------
        >>> x = mx.nd.ones((2,3))
        >>> w = mx.nd.to_dlpack_for_write(x)
        >>> type(w)
        <class 'PyCapsule'>
        >>> u = mx.nd.from_dlpack(w)
        >>> u += 1
        >>> x
        [[2. 2. 2.]
         [2. 2. 2.]]
        <NDArray 2x3 @cpu(0)>
        """
        return to_dlpack_for_write(self) 
Example #4
Source File: _ffi.py    From oscrypto with MIT License 6 votes vote down vote up
def new(library, type_, value=None):
        is_pointer, is_array, type_ = _type_info(library, type_)
        if is_array:
            if is_array is True:
                type_ = type_ * value
                value = None
            else:
                type_ = type_ * is_array

        params = []
        if value is not None:
            params.append(value)
        output = type_(*params)

        if is_pointer:
            output = pointer(output)

        return output 
Example #5
Source File: block_manager.py    From sawtooth-core with Apache License 2.0 6 votes vote down vote up
def _check_error(res):
    if res == ErrorCode.Success:
        return

    if res == ErrorCode.NullPointerProvided:
        raise TypeError("Provided null pointer(s)")
    elif res == ErrorCode.StopIteration:
        raise StopIteration()
    elif res == ErrorCode.MissingPredecessor:
        raise MissingPredecessor("Missing predecessor")
    elif res == ErrorCode.MissingPredecessorInBranch:
        raise MissingPredecessorInBranch("Missing predecessor")
    elif res == ErrorCode.MissingInput:
        raise MissingInput("Missing input to put method")
    elif res == ErrorCode.UnknownBlock:
        raise UnknownBlock("Block was unknown")
    elif res == ErrorCode.InvalidInputString:
        raise TypeError("Invalid block store name provided")
    else:
        raise Exception("There was an unknown error: {}".format(res)) 
Example #6
Source File: ndarray.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def to_dlpack_for_read(self):
        """Returns a reference view of NDArray that represents as DLManagedTensor until
        all previous write operations on the current array are finished.

        Returns
        -------
        PyCapsule (the pointer of DLManagedTensor)
            a reference view of NDArray that represents as DLManagedTensor.

        Examples
        --------
        >>> x = mx.nd.ones((2,3))
        >>> y = mx.nd.to_dlpack_for_read(x)
        >>> type(y)
        <class 'PyCapsule'>
        >>> z = mx.nd.from_dlpack(y)
        >>> z
        [[1. 1. 1.]
         [1. 1. 1.]]
        <NDArray 2x3 @cpu(0)>
        """
        return to_dlpack_for_read(self) 
Example #7
Source File: merkle.py    From sawtooth-core with Apache License 2.0 6 votes vote down vote up
def __contains__(self, item):
        """Does the tree contain an address.

        Args:
            item (str): An address.

        Returns:
            (bool): True if it does contain, False otherwise.
        """
        try:
            _libexec('merkle_db_contains', self.pointer,
                     item.encode())
            # No error implies found
            return True
        except KeyError:
            return False 
Example #8
Source File: ndarray.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def attach_grad(self, grad_req='write', stype=None):
        """Attach a gradient buffer to this NDArray, so that `backward`
        can compute gradient with respect to it.

        Parameters
        ----------
        grad_req : {'write', 'add', 'null'}
            How gradient will be accumulated.
            - 'write': gradient will be overwritten on every backward.
            - 'add': gradient will be added to existing value on every backward.
            - 'null': do not compute gradient for this NDArray.
        stype : str, optional
            The storage type of the gradient array. Defaults to the same stype of this NDArray.
        """
        from . import zeros as _zeros
        if stype is not None:
            grad = _zeros(self.shape, stype=stype)
        else:
            grad = op.zeros_like(self)  # pylint: disable=undefined-variable
        grad_req = _GRAD_REQ_MAP[grad_req]
        check_call(_LIB.MXAutogradMarkVariables(
            1, ctypes.pointer(self.handle),
            ctypes.pointer(mx_uint(grad_req)),
            ctypes.pointer(grad.handle))) 
Example #9
Source File: winapi.py    From cWMI with Apache License 2.0 6 votes vote down vote up
def SafeArrayAccessData(sa):
    prototype = ctypes.WINFUNCTYPE(
        HRESULT,
        ctypes.POINTER(SAFEARRAY),
        ctypes.POINTER(wintypes.LPVOID)
    )

    paramflags = (
        (_In_, 'psa'),
        (_Out_, 'ppvData', ctypes.pointer(wintypes.LPVOID(None))),
    )

    _SafeArrayAccessData = prototype(('SafeArrayAccessData', oleaut32), paramflags)
    _SafeArrayAccessData.errcheck = RAISE_NON_ZERO_ERR
    return_obj = _SafeArrayAccessData(sa)
    return return_obj.contents 
Example #10
Source File: key.py    From checklocktimeverify-demos with GNU General Public License v3.0 6 votes vote down vote up
def verify(self, hash, sig): # pylint: disable=redefined-builtin
        """Verify a DER signature"""
        if not sig:
          return False

        # New versions of OpenSSL will reject non-canonical DER signatures. de/re-serialize first.
        norm_sig = ctypes.c_void_p(0)
        _ssl.d2i_ECDSA_SIG(ctypes.byref(norm_sig), ctypes.byref(ctypes.c_char_p(sig)), len(sig))

        derlen = _ssl.i2d_ECDSA_SIG(norm_sig, 0)
        if derlen == 0:
            _ssl.ECDSA_SIG_free(norm_sig)
            return False

        norm_der = ctypes.create_string_buffer(derlen)
        _ssl.i2d_ECDSA_SIG(norm_sig, ctypes.byref(ctypes.pointer(norm_der)))
        _ssl.ECDSA_SIG_free(norm_sig)

        # -1 = error, 0 = bad sig, 1 = good
        return _ssl.ECDSA_verify(0, hash, len(hash), norm_der, derlen, self.k) == 1 
Example #11
Source File: pomp_loop_thread.py    From olympe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _add_fd_to_loop(self, fd, cb, fd_events, userdata=None):
        if cb is None:
            self.logger.info(
                "Cannot add fd '{}' to pomp loop without "
                "a valid callback function".format(fd)
            )
            return None
        self.fd_userdata[fd] = userdata
        userdata = ctypes.cast(
            ctypes.pointer(ctypes.py_object(userdata)), ctypes.c_void_p
        )
        self.c_fd_userdata[fd] = userdata
        self.pomp_fd_callbacks[fd] = od.pomp_fd_event_cb_t(cb)
        res = od.pomp_loop_add(
            self.pomp_loop,
            ctypes.c_int32(fd),
            od.uint32_t(int(fd_events)),
            self.pomp_fd_callbacks[fd],
            userdata
        )
        if res != 0:
            raise RuntimeError(
                "Cannot add fd '{}' to pomp loop: {} ({})".format(
                    fd, os.strerror(-res), res)
            ) 
Example #12
Source File: pdraw.py    From olympe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_session_metadata(self):
        """
        Returns a dictionary of video stream session metadata
        """
        if self.pdraw is None:
            self.logger.error("Error Pdraw interface seems to be destroyed")
            return None

        if self.session_metadata:
            return self.session_metadata

        vmeta_session = od.struct_vmeta_session()
        res = od.pdraw_get_peer_session_metadata(
            self.pdraw, ctypes.pointer(vmeta_session))
        if res != 0:
            msg = "Unable to get sessions metata"
            self.logger.error(msg)
            return None
        self.session_metadata = od.struct_vmeta_session.as_dict(
            vmeta_session)
        return self.session_metadata 
Example #13
Source File: discovery.py    From olympe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def from_arsdk_device(cls, backend, device):
        device_info = ctypes.POINTER(od.struct_arsdk_device_info)()
        res = od.arsdk_device_get_info(device, ctypes.pointer(device_info))
        if res != 0:
            raise RuntimeError("ERROR: failed to get device info: {}".format(res))
        return Device(
            serial=od.string_cast(device_info.contents.id) or "",
            name=od.string_cast(device_info.contents.name) or "",
            device_type=int(device_info.contents.type),
            ip_addr=od.string_cast(device_info.contents.addr) or "",
            port=int(device_info.contents.port),
            proto_v=int(getattr(device_info.contents, "proto_v", 1)),
            state=DeviceState(device_info.contents.state),
            json=od.string_cast(device_info.contents.json) or "",
            arsdk_device=device,
            backend=backend,
        ) 
Example #14
Source File: discovery.py    From olympe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _create_discovery(self):
        """
        Start net discovery in order to detect devices
        """
        discovery = od.POINTER_T(od.struct_arsdk_discovery_net)()

        res = od.arsdk_discovery_net_new(
            self._backend._arsdk_ctrl,
            self._backend._backend_net,
            ctypes.pointer(self.discovery_cfg),
            od.char_pointer_cast(self.ip_addr),
            ctypes.byref(discovery),
        )
        if res != 0:
            self.logger.error("arsdk_discovery_net_new: {}".format(res))
            return None
        return discovery 
Example #15
Source File: drone.py    From olympe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _create_command_interface(self):
        """
        Create a command interface to send command to the device
        """

        cmd_itf = od.POINTER_T(od.struct_arsdk_cmd_itf)()

        res = od.arsdk_device_create_cmd_itf(
            self._device.arsdk_device,
            self._cmd_itf_cbs,
            ctypes.pointer(cmd_itf))

        if res != 0:
            self.logger.error(
                "Error while creating command interface: {}".format(res))
            cmd_itf = None
        else:
            self.logger.info("Command interface has been created: itf=%s"
                              % self._cmd_itf)

        return cmd_itf 
Example #16
Source File: shader.py    From ratcave with MIT License 6 votes vote down vote up
def _createShader(self, strings, shadertype):

        # create the shader handle
        shader = gl.glCreateShader(shadertype)

        # convert the source strings into a ctypes pointer-to-char array, and upload them
        # this is deep, dark, dangerous black magick - don't try stuff like this at home!
        strings = tuple(s.encode('ascii') for s in strings)  # Nick added, for python3
        src = (c_char_p * len(strings))(*strings)
        gl.glShaderSource(shader, len(strings), cast(pointer(src), POINTER(POINTER(c_char))), None)
        # compile the shader
        gl.glCompileShader(shader)

        # retrieve the compile status
        compile_success = c_int(0)
        gl.glGetShaderiv(shader, gl.GL_COMPILE_STATUS, byref(compile_success))

        # if compilation failed, print the log
        if compile_success:
            gl.glAttachShader(self.id, shader)
        else:
            gl.glGetShaderiv(shader, gl.GL_INFO_LOG_LENGTH, byref(compile_success))  # retrieve the log length
            buffer = create_string_buffer(compile_success.value)  # create a buffer for the log
            gl.glGetShaderInfoLog(shader, compile_success, None, buffer)  # retrieve the log text
            print(buffer.value)  # print the log to the console 
Example #17
Source File: block_store.py    From sawtooth-core with Apache License 2.0 6 votes vote down vote up
def chain_head(self):
        """
        Return the head block of the current chain.
        """
        (vec_ptr, vec_len, vec_cap) = ffi.prepare_vec_result()

        try:
            _libexec(
                'commit_store_get_chain_head',
                self.pointer,
                ctypes.byref(vec_ptr),
                ctypes.byref(vec_len),
                ctypes.byref(vec_cap))
        except ValueError:
            return None

        return self.deserialize_block(
            ffi.from_rust_vec(vec_ptr, vec_len, vec_cap)) 
Example #18
Source File: smbus.py    From Adafruit_Python_PureIO with MIT License 6 votes vote down vote up
def make_i2c_rdwr_data(messages):
    """Utility function to create and return an i2c_rdwr_ioctl_data structure
    populated with a list of specified I2C messages.  The messages parameter
    should be a list of tuples which represent the individual I2C messages to
    send in this transaction.  Tuples should contain 4 elements: address value,
    flags value, buffer length, ctypes c_uint8 pointer to buffer.
    """
    # Create message array and populate with provided data.
    msg_data_type = i2c_msg * len(messages)
    msg_data = msg_data_type()
    for i, message in enumerate(messages):
        msg_data[i].addr = message[0] & 0x7F
        msg_data[i].flags = message[1]
        msg_data[i].len = message[2]
        msg_data[i].buf = message[3]
    # Now build the data structure.
    data = i2c_rdwr_ioctl_data()
    data.msgs = msg_data
    data.nmsgs = len(messages)
    return data


# Create an interface that mimics the Python SMBus API. 
Example #19
Source File: test_ctypeslib.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_reference_cycles(self):
        # related to gh-6511
        import ctypes

        # create array to work with
        # don't use int/long to avoid running into bpo-10746
        N = 100
        a = np.arange(N, dtype=np.short)

        # get pointer to array
        pnt = np.ctypeslib.as_ctypes(a)

        with np.testing.assert_no_gc_cycles():
            # decay the array above to a pointer to its first element
            newpnt = ctypes.cast(pnt, ctypes.POINTER(ctypes.c_short))
            # and construct an array using this data
            b = np.ctypeslib.as_array(newpnt, (N,))
            # now delete both, which should cleanup both objects
            del newpnt, b 
Example #20
Source File: key.py    From checklocktimeverify-demos with GNU General Public License v3.0 6 votes vote down vote up
def verify(self, hash, sig): # pylint: disable=redefined-builtin
        """Verify a DER signature"""
        if not sig:
          return False

        # New versions of OpenSSL will reject non-canonical DER signatures. de/re-serialize first.
        norm_sig = ctypes.c_void_p(0)
        _ssl.d2i_ECDSA_SIG(ctypes.byref(norm_sig), ctypes.byref(ctypes.c_char_p(sig)), len(sig))

        derlen = _ssl.i2d_ECDSA_SIG(norm_sig, 0)
        if derlen == 0:
            _ssl.ECDSA_SIG_free(norm_sig)
            return False

        norm_der = ctypes.create_string_buffer(derlen)
        _ssl.i2d_ECDSA_SIG(norm_sig, ctypes.byref(ctypes.pointer(norm_der)))
        _ssl.ECDSA_SIG_free(norm_sig)

        # -1 = error, 0 = bad sig, 1 = good
        return _ssl.ECDSA_verify(0, hash, len(hash), norm_der, derlen, self.k) == 1 
Example #21
Source File: rmTimeUtils.py    From rainmachine-developer-resources with GNU General Public License v3.0 6 votes vote down vote up
def monotonicTime(self, asSeconds = True):
        t = timespec()
        if self.clock_gettime(rmMonotonicTime.CLOCK_MONOTONIC_RAW , ctypes.pointer(t)) != 0:
            errno_ = ctypes.get_errno()
            if self.fallback:
                log.info("Monotonic Clock Error ! Reverting to time.time() fallback")
                return self.monotonicFallback(asSeconds)
            else:
                raise OSError(errno_, os.strerror(errno_))

        if asSeconds:
            return t.tv_sec

        return t.tv_sec + t.tv_nsec * 1e-9


#-----------------------------------------------------------------------------------------------
#
#
# 
Example #22
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 #23
Source File: block_manager.py    From sawtooth-core with Apache License 2.0 5 votes vote down vote up
def branch(self, tip):
        return _BranchIterator(self.pointer, tip) 
Example #24
Source File: ifaces.py    From kano-toolset with GNU General Public License v2.0 5 votes vote down vote up
def get_iface(iface_type_str):
    iface_type = ctypes.create_string_buffer(iface_type_str)

    str_p = ctypes.c_char_p()
    pt = ctypes.pointer(str_p)

    if LIB.select_iface(iface_type, pt) != 0:
        return False

    return ctypes.string_at(str_p) 
Example #25
Source File: block_store.py    From sawtooth-core with Apache License 2.0 5 votes vote down vote up
def __init__(self, database):
        super().__init__('commit_store_drop')
        _libexec(
            'commit_store_new',
            database.pointer,
            ctypes.byref(self.pointer)) 
Example #26
Source File: system.py    From stem with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _set_argv(process_name: str) -> None:
  """
  Overwrites our argv in a similar fashion to how it's done in C with:
  strcpy(argv[0], 'new_name');
  """

  if Py_GetArgcArgv is None:
    return

  global _PROCESS_NAME

  # both gets the current process name and initializes _MAX_NAME_LENGTH

  current_name = get_process_name()

  argv, argc = ctypes.c_int(0), argc_t()
  Py_GetArgcArgv(argv, ctypes.pointer(argc))

  if len(process_name) > _MAX_NAME_LENGTH:
    raise IOError("Can't rename process to something longer than our initial name (this would overwrite memory used for the env)")

  # space we need to clear
  zero_size = max(len(current_name), len(process_name))

  ctypes.memset(argc.contents, 0, zero_size + 1)  # null terminate the string's end
  process_name_encoded = process_name.encode('utf8')
  ctypes.memmove(argc.contents, process_name_encoded, len(process_name))
  _PROCESS_NAME = process_name 
Example #27
Source File: block_store.py    From sawtooth-core with Apache License 2.0 5 votes vote down vote up
def _get_data_by_num(self, object_id, ffi_fn_name):
        (vec_ptr, vec_len, vec_cap) = ffi.prepare_vec_result()
        _pylibexec(ffi_fn_name,
                   self.pointer,
                   ctypes.c_ulonglong(object_id),
                   ctypes.byref(vec_ptr),
                   ctypes.byref(vec_len),
                   ctypes.byref(vec_cap))

        return ffi.from_rust_vec(vec_ptr, vec_len, vec_cap) 
Example #28
Source File: block_store.py    From sawtooth-core with Apache License 2.0 5 votes vote down vote up
def _get_data_by_id(self, object_id, ffi_fn_name):
        (vec_ptr, vec_len, vec_cap) = ffi.prepare_vec_result()
        _pylibexec(ffi_fn_name,
                   self.pointer,
                   ctypes.c_char_p(object_id.encode()),
                   ctypes.byref(vec_ptr),
                   ctypes.byref(vec_len),
                   ctypes.byref(vec_cap))

        return ffi.from_rust_vec(vec_ptr, vec_len, vec_cap) 
Example #29
Source File: block_store.py    From sawtooth-core with Apache License 2.0 5 votes vote down vote up
def put_blocks(self, blocks):
        c_put_items = (ctypes.POINTER(_PutEntry) * len(blocks))()
        for (i, block) in enumerate(blocks):
            c_put_items[i] = ctypes.pointer(_PutEntry.new(
                block.SerializeToString(),
            ))

        _libexec('commit_store_put_blocks',
                 self.pointer,
                 c_put_items, ctypes.c_size_t(len(blocks))) 
Example #30
Source File: keyboard.py    From Windows-Sound-Manager with MIT License 5 votes vote down vote up
def keyDown(keyCode):
        """
        Key down wrapper
        :param keyCode: int
        :return: void
        """
        extra = ctypes.c_ulong(0)
        ii_ = Input_I()
        ii_.ki = KeyBdInput(keyCode, 0x48, 0, 0, ctypes.pointer(extra) )
        x = Input( ctypes.c_ulong(1), ii_ )
        SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))