Ejemplo n.º 1
0
def Put(data, format):
    try:
        hCd = ga(GHND, len(bytes(data)) + sizeof(c_wchar()))
    except TypeError:
        hCd = ga(GHND, len(bytes(data, 'ascii')) + sizeof(c_wchar()))

    pchData = gl(hCd)

    try:
        strcpy(c_char_p(pchData), bytes(data))
    except TypeError:
        strcpy(c_char_p(pchData), bytes(data, 'ascii'))

    gul(hCd)
    scd(c_int(format), hCd)
Ejemplo n.º 2
0
def Put(data, format):
    try:
        hCd = ga(GHND, len(bytes(data)) + sizeof(c_wchar()))
    except TypeError:
        hCd = ga(GHND, len(bytes(data, 'ascii')) + sizeof(c_wchar()))

    pchData = gl(hCd)

    try:
        strcpy(c_char_p(pchData), bytes(data))
    except TypeError:
        strcpy(c_char_p(pchData), bytes(data, 'ascii'))

    gul(hCd)
    scd(c_int(format), hCd)
Ejemplo n.º 3
0
    def prg_do_channel(self, port='0', line='0', value=(0, 0, 0, 0, 0), samplerate=10000):
        task_name = ctypes.c_wchar()
        ch_name = self.device_name+'/port'+port+'/line'+line
        print(ch_name)
        sample_per_ch = ctypes.c_ulonglong(len(value))
        sample_written = ctypes.c_ulonglong(10)
        data_array = (ctypes.c_uint8 * len(value))(*value)
        flag_task_done = ctypes.c_bool(0)

        self.daq_mx_dll.DAQmxCreateTask("j", ctypes.byref(self.task_handle))
        self.daq_mx_dll.DAQmxGetTaskName(self.task_handle, ctypes.byref(task_name),
                                         ctypes.c_uint32(32))  # get Task name
        self.check_response(self.daq_mx_dll.DAQmxCreateDOChan(self.task_handle,
                                                              ch_name.encode('utf-8'),
                                                              "",
                                                              self.line_grouping))
        self.check_response(self.daq_mx_dll.DAQmxCfgSampClkTiming(self.task_handle,
                                                                  self.ref_clock.encode('utf-8'),
                                                                  ctypes.c_double(samplerate),
                                                                  self.active_edge,
                                                                  self.sample_mode,
                                                                  sample_per_ch))
        self.check_response(self.daq_mx_dll.DAQmxWriteDigitalU8(self.task_handle,
                                                                sample_per_ch,
                                                                ctypes.c_bool(0),  # autostart
                                                                self.timeout,
                                                                ctypes.c_bool(0),  # bool32 dataLayout/gr by ch or line
                                                                data_array,  # uInt8 writeArray[],
                                                                ctypes.byref(sample_written),  # number of sample writen
                                                                None))
        self.check_response(self.daq_mx_dll.DAQmxStartTask(self.task_handle))
        while flag_task_done.value == ctypes.c_bool(0).value:
            self.daq_mx_dll.DAQmxIsTaskDone(self.task_handle, ctypes.byref(flag_task_done))
        self.daq_mx_dll.DAQmxStopTask(self.task_handle)
        self.daq_mx_dll.DAQmxClearTask(self.task_handle)
Ejemplo n.º 4
0
 def clear_screen(self, param):
     mode = to_int(param, 0)
     sbinfo = self.screen_buffer_info()
     if mode == 1:  # Clear from begining of screen to cursor position
         clear_start = COORD(0, 0)
         clear_length = sbinfo.CursorPosition.X * sbinfo.CursorPosition.Y
     elif mode == 2:  # Clear entire screen and return cursor to home
         clear_start = COORD(0, 0)
         clear_length = sbinfo.Size.X * sbinfo.Size.Y
         windll.kernel32.SetConsoleCursorPosition(
             self.hconsole, clear_start)
     else:  # Clear from cursor position to end of screen
         clear_start = sbinfo.CursorPosition
         clear_length = ((sbinfo.Size.X - sbinfo.CursorPosition.X) +
                         sbinfo.Size.X *
                         (sbinfo.Size.Y - sbinfo.CursorPosition.Y))
     chars_written = c_ulong()
     windll.kernel32.FillConsoleOutputCharacterW(
         self.hconsole, c_wchar(' '), clear_length, clear_start,
         byref(chars_written))
     windll.kernel32.FillConsoleOutputAttribute(self.hconsole,
                                                sbinfo.Attributes,
                                                clear_length,
                                                clear_start,
                                                byref(chars_written))
Ejemplo n.º 5
0
def ctypes_wrapper(player_lib, move, c_battlefield, field_size, char):
    """
        Обертка для отловки segmentation fault.
    """

    move.value = player_lib.xogame(
        c_battlefield, ctypes.c_int(field_size), ctypes.c_wchar(char))
Ejemplo n.º 6
0
 def clear_line(self, param):
     mode = param and int(param) or 0
     sbinfo = self.screen_buffer_info()
     if mode == 1:  # Clear from beginning of line to cursor position
         line_start = COORD(0, sbinfo.CursorPosition.Y)
         line_length = sbinfo.Size.X
     elif mode == 2:  # Clear entire line
         line_start = COORD(sbinfo.CursorPosition.X, sbinfo.CursorPosition.Y)
         line_length = sbinfo.Size.X - sbinfo.CursorPosition.X
     else:  # Clear from cursor position to end of line
         line_start = sbinfo.CursorPosition
         line_length = sbinfo.Size.X - sbinfo.CursorPosition.X
     chars_written = c_ulong()
     windll.kernel32.FillConsoleOutputCharacterW(
         self.hconsole,
         c_wchar(" "),
         line_length,
         line_start,
         byref(chars_written),
     )
     windll.kernel32.FillConsoleOutputAttribute(
         self.hconsole,
         sbinfo.Attributes,
         line_length,
         line_start,
         byref(chars_written),
     )
Ejemplo n.º 7
0
def renderable_line(value, tab_stop=DEFAULT_TAB_STOP, max_width=None):
    '''
    Convert a unicode string into a line that can be rendered on the
    terminal, and also compute the line width as it will be displayed on the
    terminal.

    Returns the renderable line, and the line width.

    The renderable line is the line with any non-printing control characters
    stripped out, and stopping at the first character that would cause the
    terminal to change lines (such as a newline or other vertical spacing
    character).  Tabs are expanded with spaces, using the specified tab stop
    width.

    The returned width indicates how many columns the line will take up on the
    terminal, and accounts for 0-width characters and multi-cell wide
    characters.  Note that not all terminals render characters the same way, so
    this may not be 100% accurate for all terminals.
    '''
    libc = get_libc()

    result = []
    width = 0
    for char in value:
        if max_width is not None and width >= max_width:
            break

        char_width = libc.wcwidth(ctypes.c_wchar(char))
        if char_width >= 0:
            # Common case: not a control character
            new_width = width + char_width
            # If we have a multi-cell character that would make us
            # exceed the width, stop before appending it.
            if max_width is not None and new_width > max_width:
                break
            result.append(char)
            width = new_width
            continue

        # This is a control character.  If it is a vertical separator
        # (that would cause the terminal to move forwards or backwards a
        # line), truncate the line here.
        if char in _VERTICAL_SEPARATORS:
            break

        # Expand tabs to spaces
        if char == '\t':
            next_width = next_tab_stop(width, tab_stop)
            if max_width is not None:
                next_width = max(next_width, max_width)
            num_spaces = next_width - width
            result.extend([' '] * num_spaces)
            width = next_width
            continue

        # If we are still here this is a non-printing control character.
        # Just skip it.
        continue

    return ''.join(result), width
Ejemplo n.º 8
0
 def _get_initial_keycode(cls, char):
     layout = windll.user32.GetKeyboardLayout(0)
     if isinstance(char, str) and PY2:
         code = windll.user32.VkKeyScanExA(c_char(char), layout)
     elif isinstance(char, text_type):  # unicode for PY2, str for PY3
         code = windll.user32.VkKeyScanExW(c_wchar(char), layout)
     else:
         code = -1
     if code == -1:
         raise ValueError("Unknown char: %r" % char)
     return code
Ejemplo n.º 9
0
def read_wchar(
    hProcess,
    address,
):
    ReadBuffer = ctypes.c_wchar()
    lpBuffer = ctypes.byref(ReadBuffer)
    nSize = ctypes.sizeof(ReadBuffer)
    bytesRead = ctypes.c_ulong(0)

    ctypes.windll.kernel32.ReadProcessMemory(hProcess, address, lpBuffer,
                                             nSize, bytesRead)
    return ReadBuffer.value
Ejemplo n.º 10
0
    def xget_virtual_keycode(cls, char):
        if isinstance(char, str):
            code = windll.user32.VkKeyScanA(c_char(char))
        else:
            code = windll.user32.VkKeyScanW(c_wchar(char))
        if code == -1:
            raise ValueError("Unknown char: %r" % char)

        # Construct a list of the virtual key code and modifiers.
        codes = [code & 0x00ff]
        if   code & 0x0100: codes.append(cls.shift_code)
        elif code & 0x0200: codes.append(cls.ctrl_code)
        elif code & 0x0400: codes.append(cls.alt_code)
        return codes
Ejemplo n.º 11
0
def Put(data, format):
    if format == CF_UNICODETEXT:
        hCd = ga(GHND, len(bytes(data)) + sizeof(c_char()))
    else:
        hCd = ga(GHND, len(bytes(data)) + sizeof(c_wchar()))

    pchData = gl(hCd)

    if format == CF_UNICODETEXT:
        wcscpy(c_wchar_p(pchData), bytes(data))
    else:
        strcpy(c_char_p(pchData), bytes(data))
    gul(hCd)
    scd(c_int(format), hCd, 0, False)
Ejemplo n.º 12
0
def Put(data, format):
    if format == CF_UNICODETEXT:
        hCd = ga(GHND, len(bytes(data)) + sizeof(c_char()))
    else:
        hCd = ga(GHND, len(bytes(data)) + sizeof(c_wchar()))

    pchData = gl(hCd)

    if format == CF_UNICODETEXT:
        wcscpy(c_wchar_p(pchData), bytes(data))
    else:
        strcpy(c_char_p(pchData), bytes(data))
    gul(hCd)
    scd(c_int(format), hCd, 0, False)
Ejemplo n.º 13
0
 def SPI_pattern(self, CLKLine='0', SDILine='3',CSNLine='2', SDOLine='4', SPI_pattern=(0, 0, 0, 0, 0), samplerate=10000):
     task_name = ctypes.c_wchar()
     CLK_channel = self.device_name+'/port'+'0'+'/line'+CLKLine
     SDI_channel = self.device_name+'/port'+'0'+'/line'+SDILine
     CSN_channel = self.device_name+'/port'+'0'+'/line'+CSNLine
     sample_per_ch = ctypes.c_ulonglong(int(len(SPI_pattern)/3))
     sample_written = ctypes.c_ulonglong(10)
     data_array = (ctypes.c_uint8 * len(SPI_pattern))(*SPI_pattern)
     flag_task_done = ctypes.c_bool(0)
     self.daq_mx_dll.DAQmxCreateTask("j", ctypes.byref(self.task_handle))
     self.daq_mx_dll.DAQmxGetTaskName(self.task_handle, ctypes.byref(task_name),
                                      ctypes.c_uint32(32))  # get Task name
     self.check_response(self.daq_mx_dll.DAQmxCreateDOChan(self.task_handle,
                                                           CLK_channel.encode('utf-8'),
                                                           str("CLK").encode('utf-8'),
                                                           self.line_grouping))
     self.check_response(self.daq_mx_dll.DAQmxCreateDOChan(self.task_handle,
                                                           SDI_channel.encode('utf-8'),
                                                           str("SDI").encode('utf-8'),
                                                           self.line_grouping))
     self.check_response(self.daq_mx_dll.DAQmxCreateDOChan(self.task_handle,
                                                           CSN_channel.encode('utf-8'),
                                                           str("CSN").encode('utf-8'),
                                                           self.line_grouping))
     self.check_response(self.daq_mx_dll.DAQmxCfgSampClkTiming(self.task_handle,
                                                               self.ref_clock.encode('utf-8'),
                                                               ctypes.c_double(samplerate),
                                                               self.active_edge,
                                                               self.sample_mode,
                                                               sample_per_ch))
     self.check_response(self.daq_mx_dll.DAQmxDisableStartTrig(self.task_handle))
     #self.check_response(self.daq_mx_dll.DAQmxCfgDigEdgeStartTrig(self.task_handle,
      #                                                            self.ref_clock.encode('utf-8'),  # trig signal
      #                                                            self.active_edge))  # trigger edge
     print(sample_per_ch.value)
     print(data_array[1])
     self.check_response(self.daq_mx_dll.DAQmxWriteDigitalU8(self.task_handle,
                                                             sample_per_ch,
                                                             ctypes.c_bool(0),  # autostart
                                                             self.timeout,
                                                             ctypes.c_bool(0),  # bool32 dataLayout/ropu by ch ore
                                                             data_array,
                                                             ctypes.byref(sample_written),  # number of sample writen
                                                             None))
     self.check_response(self.daq_mx_dll.DAQmxStartTask(self.task_handle))
     while flag_task_done.value == ctypes.c_bool(0).value:
         self.daq_mx_dll.DAQmxIsTaskDone(self.task_handle, ctypes.byref(flag_task_done))
     self.daq_mx_dll.DAQmxStopTask(self.task_handle)
     self.daq_mx_dll.DAQmxClearTask(self.task_handle)
Ejemplo n.º 14
0
		def clear_line(self, param):
			mode = param and int(param) or 0
			sbinfo = self.screen_buffer_info()
			if mode == 1: # Clear from begining of line to cursor position
				line_start = COORD(0, sbinfo.CursorPosition.Y)
				line_length = sbinfo.Size.X
			elif mode == 2: # Clear entire line
				line_start = COORD(sbinfo.CursorPosition.X, sbinfo.CursorPosition.Y)
				line_length = sbinfo.Size.X - sbinfo.CursorPosition.X
			else: # Clear from cursor position to end of line
				line_start = sbinfo.CursorPosition
				line_length = sbinfo.Size.X - sbinfo.CursorPosition.X
			chars_written = c_ulong()
			windll.kernel32.FillConsoleOutputCharacterW(self.hconsole, c_wchar(' '), line_length, line_start, byref(chars_written))
			windll.kernel32.FillConsoleOutputAttribute(self.hconsole, sbinfo.Attributes, line_length, line_start, byref(chars_written))
Ejemplo n.º 15
0
		def clear_screen(self, param):
			mode = to_int(param, 0)
			sbinfo = self.screen_buffer_info()
			if mode == 1: # Clear from begining of screen to cursor position
				clear_start = COORD(0, 0)
				clear_length = sbinfo.CursorPosition.X * sbinfo.CursorPosition.Y
			elif mode == 2: # Clear entire screen and return cursor to home
				clear_start = COORD(0, 0)
				clear_length = sbinfo.Size.X * sbinfo.Size.Y
				windll.kernel32.SetConsoleCursorPosition(self.hconsole, clear_start)
			else: # Clear from cursor position to end of screen
				clear_start = sbinfo.CursorPosition
				clear_length = ((sbinfo.Size.X - sbinfo.CursorPosition.X) + sbinfo.Size.X * (sbinfo.Size.Y - sbinfo.CursorPosition.Y))
			chars_written = c_ulong()
			windll.kernel32.FillConsoleOutputCharacterW(self.hconsole, c_wchar(' '), clear_length, clear_start, byref(chars_written))
			windll.kernel32.FillConsoleOutputAttribute(self.hconsole, sbinfo.Attributes, clear_length, clear_start, byref(chars_written))
Ejemplo n.º 16
0
    def get_keycode_and_modifiers(cls, char):
        layout = windll.user32.GetKeyboardLayout(0)
        if isinstance(char, str):
            code = windll.user32.VkKeyScanExA(c_char(char), layout)
        else:
            code = windll.user32.VkKeyScanExW(c_wchar(char), layout)
        if code == -1:
            raise ValueError("Unknown char: %r" % char)

        # Construct a list of the virtual key code and modifiers.
        modifiers = []
        if code & 0x0100: modifiers.append(cls.shift_code)
        if code & 0x0200: modifiers.append(cls.ctrl_code)
        if code & 0x0400: modifiers.append(cls.alt_code)
        code &= 0x00ff
        return code, modifiers
Ejemplo n.º 17
0
def insline():
    srSource = ctypes.wintypes._SMALL_RECT()
    ciFill = CHAR_INFO()
    hConOut = _getconout()
    csbi = _getscreeninfo()
    dwDest = ctypes.wintypes._COORD()
    srSource.Top = csbi.dwCursorPosition.Y
    srSource.Left = csbi.srWindow.Left
    srSource.Bottom = csbi.srWindow.Bottom
    srSource.Right = csbi.srWindow.Right
    dwDest.X = csbi.srWindow.Left
    dwDest.Y = csbi.dwCursorPosition.Y
    ciFill.Char.UnicodeChar = ctypes.c_wchar(_A_BLANK)
    ciFill.Attributes = csbi.wAttributes
    kernel32.ScrollConsoleScreenBufferW(hConOut, ctypes.byref(srSource),
                                        LPDWORD(ctypes.c_ulong(0)), dwDest,
                                        ctypes.byref(ciFill))
Ejemplo n.º 18
0
def Put(data, format):
    # Ensure we are using a bytes object.
    data = bytes(data)
    # Allocate global memory, including space for terminator.
    # GHND is GMEM_MOVEABLE (required) and GMEM_ZEROINIT (convenient).
    hCd = ga(GHND, c_size_t(len(data) + sizeof(c_wchar())))

    # Lock the memory and get a pointer to it.
    pchData = gl(c_void_p(hCd))
    if not pchData:
        code = gle()
        raise Exception('Failed to lock: %r' % code)

    # Move data into global memory.
    memmove(c_void_p(pchData), data, c_size_t(len(data)))
    # Unlock.
    gul(c_void_p(hCd))
    # Set clipboard data.
    scd(format, c_void_p(hCd))
Ejemplo n.º 19
0
def Put(data, format):
    # Ensure we are using a bytes object.
    data = bytes(data)
    # Allocate global memory, including space for terminator.
    # GHND is GMEM_MOVEABLE (required) and GMEM_ZEROINIT (convenient).
    hCd = ga(c_int(GHND), c_size_t(len(data) + sizeof(c_wchar())))

    # Lock the memory and get a pointer to it.
    pchData = gl(c_void_p(hCd))
    if not pchData:
        code = gle()
        raise Exception("Failed to lock: %r" % code)

    # Move data into global memory.
    memmove(c_void_p(pchData), data, c_size_t(len(data)))
    # Unlock.
    gul(c_void_p(hCd))
    # Set clipboard data.
    scd(c_int(format), c_void_p(hCd))
Ejemplo n.º 20
0
 def clear_screen(self, param):
     mode = to_int(param, 0)
     sbinfo = self.screen_buffer_info()
     if mode == 1:
         clear_start = COORD(0, 0)
         clear_length = sbinfo.CursorPosition.X * sbinfo.CursorPosition.Y
     elif mode == 2:
         clear_start = COORD(0, 0)
         clear_length = sbinfo.Size.X * sbinfo.Size.Y
         windll.kernel32.SetConsoleCursorPosition(self.hconsole, clear_start)
     else:
         clear_start = sbinfo.CursorPosition
         clear_length = (sbinfo.Size.X - sbinfo.CursorPosition.X) + sbinfo.Size.X * (
             sbinfo.Size.Y - sbinfo.CursorPosition.Y
         )
     chars_written = c_ulong()
     windll.kernel32.FillConsoleOutputCharacterW(
         self.hconsole, c_wchar(" "), clear_length, clear_start, byref(chars_written)
     )
     windll.kernel32.FillConsoleOutputAttribute(
         self.hconsole, sbinfo.Attributes, clear_length, clear_start, byref(chars_written)
     )
Ejemplo n.º 21
0
def create_c_objects(bytes_string, delimiter):
    """
        Создание объектов для языка СИ, используемых функцией split
        1. c_string - массив символов (char *string)
        2. c_array_string - массив, содержащий массивы символов для получаемой матрицы
        3. c_array_pointer - массив указателей на эти строки (char **matrix)
        4. c_delimiter - символ-разделитель (const char symbol)
    """

    c_string = ctypes.create_string_buffer(bytes_string)
    c_array_strings = ctypes.create_string_buffer(b' ' * WORDS_COUNT *
                                                  MAX_LEN_WORD)
    filling_lib = ctypes.CDLL("filling.so")
    c_array_pointer = (ctypes.c_char_p * WORDS_COUNT)()

    filling_lib.filling_pointers_array(c_array_pointer, c_array_strings,
                                       ctypes.c_int(MAX_LEN_WORD),
                                       ctypes.c_int(WORDS_COUNT))

    c_delimiter = ctypes.c_wchar(delimiter)

    return c_string, c_array_strings, c_array_pointer, c_delimiter
Ejemplo n.º 22
0
 def prg_ao_channel(self, line='0', value=(0, 0, 0, 0, 0), samplerate=10000, min=-1, max=10):
     task_name = ctypes.c_wchar()
     ch_name = self.device_name+'/ao'+line
     sample_per_ch = ctypes.c_ulonglong(len(value))
     sample_written = ctypes.c_ulonglong(10)
     data_array = (ctypes.c_double * len(value))(*value)
     flag_task_done = ctypes.c_bool(0)
     self.daq_mx_dll.DAQmxCreateTask("j", ctypes.byref(self.task_handle))
     self.daq_mx_dll.DAQmxGetTaskName(self.task_handle,
                                      ctypes.byref(task_name),
                                      ctypes.c_uint32(32))  # get Task name
     self.check_response(self.daq_mx_dll.DAQmxCreateAOVoltageChan(self.task_handle,
                                                                  ch_name.encode('utf-8'),
                                                                  "",
                                                                  ctypes.c_double(min),
                                                                  ctypes.c_double(max),
                                                                  ctypes.c_long(10348),  # the integer for Volt units
                                                                  None))
     self.check_response(self.daq_mx_dll.DAQmxCfgSampClkTiming(self.task_handle,
                                                               self.ref_clock.encode('utf-8'),
                                                               ctypes.c_double(samplerate),
                                                               self.active_edge,
                                                               self.sample_mode,
                                                               sample_per_ch))
     self.check_response(self.daq_mx_dll.DAQmxWriteAnalogF64(self.task_handle,
                                                             sample_per_ch,
                                                             ctypes.c_bool(0),  # autostart
                                                             self.timeout,
                                                             ctypes.c_bool(0),  # bool32 dataLayout,gr by ch or line
                                                             data_array,
                                                             ctypes.byref(sample_written),  # number of sample writen
                                                             None))
     self.check_response(self.daq_mx_dll.DAQmxStartTask(self.task_handle))
     while flag_task_done.value == ctypes.c_bool(0).value:
         self.daq_mx_dll.DAQmxIsTaskDone(self.task_handle, ctypes.byref(flag_task_done))
     self.daq_mx_dll.DAQmxStopTask(self.task_handle)
     self.daq_mx_dll.DAQmxClearTask(self.task_handle)
Ejemplo n.º 23
0
def wcwidth(c):
    """
    return width of character, if string inputted, only the first character
    """
    inp = ctypes.c_wchar(c[0])
    return wide.wcwidth(inp)
Ejemplo n.º 24
0
    [ctypes.c_long(LONG_MIN)],
    [ctypes.c_longlong(LLONG_MIN)],
]
char_vals = [
    [ctypes.c_byte(0)],
    [ctypes.c_byte(-1)],
    [ctypes.c_byte(1)],
    [ctypes.c_byte(CHAR_MIN)],
    [ctypes.c_byte(CHAR_MAX)],
    [ctypes.c_char(0)],
    [ctypes.c_char(1)],
    [ctypes.c_char(UCHAR_MAX)],
]
wchar_vals = [
    [None],
    [ctypes.c_wchar(u'a')],
    [ctypes.c_wchar(u'\u262D')],
]
pointer_vals = [
    [None],
    [0],
    [ctypes.c_uint(UINT_MAX)],
    [ctypes.c_ulonglong(ULLONG_MAX)],
]
str_vals = [
    [None],
    [b''],
    [b'c'],
    [b'foo'],
]
Ejemplo n.º 25
0
def test_wchar():
    assert json.dumps(c_wchar('A'), cls=CDataJSONEncoder) == '"A"'
Ejemplo n.º 26
0
# numeric and mathematical types (CH 9)
a['DecimalType'] = decimal.Decimal(1)
a['CountType'] = itertools.count(0)
# data compression and archiving (CH 12)
a['TarInfoType'] = tarfile.TarInfo()
# generic operating system services (CH 15)
a['LoggerType'] = logging.getLogger()
a['FormatterType'] = logging.Formatter() # pickle ok
a['FilterType'] = logging.Filter() # pickle ok
a['LogRecordType'] = logging.makeLogRecord(_dict) # pickle ok
a['OptionParserType'] = _oparser = optparse.OptionParser() # pickle ok
a['OptionGroupType'] = optparse.OptionGroup(_oparser,"foo") # pickle ok
a['OptionType'] = optparse.Option('--foo') # pickle ok
if HAS_CTYPES:
    a['CCharType'] = _cchar = ctypes.c_char()
    a['CWCharType'] = ctypes.c_wchar() # fail == 2.6
    a['CByteType'] = ctypes.c_byte()
    a['CUByteType'] = ctypes.c_ubyte()
    a['CShortType'] = ctypes.c_short()
    a['CUShortType'] = ctypes.c_ushort()
    a['CIntType'] = ctypes.c_int()
    a['CUIntType'] = ctypes.c_uint()
    a['CLongType'] = ctypes.c_long()
    a['CULongType'] = ctypes.c_ulong()
    a['CLongLongType'] = ctypes.c_longlong()
    a['CULongLongType'] = ctypes.c_ulonglong()
    a['CFloatType'] = ctypes.c_float()
    a['CDoubleType'] = ctypes.c_double()
    a['CSizeTType'] = ctypes.c_size_t()
    a['CLibraryLoaderType'] = ctypes.cdll
    a['StructureType'] = _Struct
Ejemplo n.º 27
0
def main():
    diff = difflib.Differ()
    iocla_printf = ctypes.CDLL('./libprint.so').iocla_printf
    libc = ctypes.CDLL('libc.so.6')
    data_type_regex = re.compile('%*%[duxcs]')
    c_data_type = {
        '%d': lambda x: ctypes.c_int32(int(x)),
        '%u': lambda x: ctypes.c_uint32(int(x)),
        '%x': lambda x: ctypes.c_uint32(int(x)),
        '%c': lambda x: ctypes.c_wchar(string_escape(x)),
        '%s': lambda x: str.encode(string_escape(x))
    }

    if not os.path.exists(OUT_DIR):
        os.makedirs(OUT_DIR)

    print(25 * '=' + ' Tema 1 IOCLA ' + '=' * 25 + '\n')  # Total = 64

    for test_no in range(NUM_TESTS):
        with open('input/test{}'.format(test_no)) as test:
            description, *print_params = test.read().split('\n')
            fmt, *args = print_params
            for idx, identifier in enumerate(re.findall(data_type_regex, fmt)):
                if identifier.count('%') % 2 == 0:
                    continue
                else:
                    identifier = identifier[-2:]
                args[idx] = c_data_type[identifier](args[idx])
            fmt = str.encode(string_escape(fmt))

            sys_stdout = os.dup(sys.stdout.fileno())

            iocla_fd = os.open('{}/test{}.out'.format(OUT_DIR, test_no),
                               os.O_WRONLY | os.O_CREAT | os.O_TRUNC)
            os.dup2(iocla_fd, sys.stdout.fileno())
            iocla_printf_ret = iocla_printf(fmt, *args)
            libc.fflush(None)
            os.close(iocla_fd)

            libc_fd = os.open('{}/test{}.ref'.format(OUT_DIR, test_no),
                              os.O_WRONLY | os.O_CREAT | os.O_TRUNC)
            os.dup2(libc_fd, sys.stdout.fileno())
            libc_printf_ret = libc.printf(fmt, *args)
            libc.fflush(None)
            os.close(libc_fd)

            os.dup2(sys_stdout, sys.stdout.fileno())

            print('{} {} '.format(test_no, description) +
                  (55 - len(description) - test_no // 10) * '.',
                  end=' ')

            iocla_out = open('{}/test{}.out'.format(OUT_DIR, test_no),
                             'rb').read()
            try:
                iocla_out.decode('ascii')
            except:
                print(' FAIL')
                print('Your output contains non-ASCII characters')
            else:
                iocla_out = iocla_out.decode('ascii')
                libc_out = open('{}/test{}.ref'.format(OUT_DIR, test_no),
                                'r').read()
                diff = list(difflib.unified_diff(iocla_out, libc_out))

                if len(diff) == 0:
                    if iocla_printf_ret != libc_printf_ret:
                        print(' FAIL')
                        print('Your print returned {} instead of {}'.format(
                            iocla_printf_ret, libc_printf_ret))
                    else:
                        print(' PASS')
                        global PASS_TESTS
                        PASS_TESTS = PASS_TESTS + 1
                else:
                    print(' FAIL')
                    # print('\n'.join(diff))

            os.close(sys_stdout)

    print('\nTotal: {:.2f}'.format(PASS_TESTS / NUM_TESTS * 100))
Ejemplo n.º 28
0
    def render(self, text):
        
        ch = ctypes.c_wchar(text)

        # Layout rectangle; not clipped against so not terribly important.
        width = 10000
        height = self._bitmap_height
        rect = Rectf(0, self._bitmap_height 
                        - self.font.ascent + self.font.descent, 
                     width, height)

        # Set up GenericTypographic with 1 character measure range
        generic = ctypes.c_void_p()
        gdiplus.GdipStringFormatGetGenericTypographic(ctypes.byref(generic))
        format = ctypes.c_void_p()
        gdiplus.GdipCloneStringFormat(generic, ctypes.byref(format))

        # Measure advance
        bbox = Rectf()
        flags = (StringFormatFlagsMeasureTrailingSpaces | 
                 StringFormatFlagsNoClip | 
                 StringFormatFlagsNoFitBlackBox)
        gdiplus.GdipSetStringFormatFlags(format, flags)
        gdiplus.GdipMeasureString(self._graphics, ctypes.byref(ch), 1,
            self.font._gdipfont, ctypes.byref(rect), format,
            ctypes.byref(bbox), 0, 0)

        lsb = 0
        advance = int(math.ceil(bbox.width))

        # XXX HACK HACK HACK
        # Windows GDI+ is a filthy broken toy.  No way to measure the bounding
        # box of a string, or to obtain LSB.  What a joke.
        # 
        # For historical note, GDI cannot be used because it cannot composite
        # into a bitmap with alpha.
        #
        # It looks like MS have abandoned GDI and GDI+ and are finally
        # supporting accurate text measurement with alpha composition in .NET
        # 2.0 (WinForms) via the TextRenderer class; this has no C interface
        # though, so we're entirely screwed.
        # 
        # So anyway, this hack bumps up the width if the font is italic;
        # this compensates for some common fonts.  It's also a stupid waste of
        # texture memory.
    
        width = advance
        if self.font.italic:
            width += width // 2
        
        # XXX END HACK HACK HACK

        # Draw character to bitmap
        
        gdiplus.GdipGraphicsClear(self._graphics, 0x00000000)
        gdiplus.GdipDrawString(self._graphics, ctypes.byref(ch), 1,
            self.font._gdipfont, ctypes.byref(rect), format,
            self._brush)
        gdiplus.GdipFlush(self._graphics, 1)

        bitmap_data = BitmapData()
        gdiplus.GdipBitmapLockBits(self._bitmap, 
            byref(self._rect), ImageLockModeRead, self._format, 
            byref(bitmap_data))
        
        # Create buffer for RawImage
        buffer = create_string_buffer(
            bitmap_data.Stride * bitmap_data.Height)
        memmove(buffer, bitmap_data.Scan0, len(buffer))
        
        # Unlock data
        gdiplus.GdipBitmapUnlockBits(self._bitmap, byref(bitmap_data))
        
        image = pyglet.image.ImageData(width, height, 
            'BGRA', buffer, -bitmap_data.Stride)

        glyph = self.font.create_glyph(image)
        glyph.set_bearings(-self.font.descent, lsb, advance)

        return glyph
Ejemplo n.º 29
0
		library_name = 'libBearLibTerminal.so'
	elif 'darwin' in sys.platform:
		library_name = 'libBearLibTerminal.dylib'
	else:
		raise RuntimeError('Unsupported platform: ' + sys.platform)
	
	# Now actually try to load the library binary
	try:
		return ctypes.CDLL(library_path + path.sep + library_name)
	except OSError:
		raise RuntimeError('BearLibTerminal library cannot be loaded (looked for ' + library_name + ' in ' + library_path + ')')

_library = _load_library()

# wchar_t size may vary
if ctypes.sizeof(ctypes.c_wchar()) == 4:
	_wset = _library.terminal_set32
	_wprint = _library.terminal_print32
	_wmeasure = _library.terminal_measure32
	_read_wstr = _library.terminal_read_str32
	_color_from_wname = _library.color_from_name32
	_wget = _library.terminal_get32
else:
	_wset = _library.terminal_set16
	_wprint = _library.terminal_print16
	_wmeasure = _library.terminal_measure16
	_read_wstr = _library.terminal_read_str16
	_color_from_wname = _library.color_from_name16
	_wget = _library.terminal_get16

# color/bkcolor accept uint32, color_from_name returns uint32
Ejemplo n.º 30
0
# DAQmx_Val_FiniteSamps = 10178 Acquire or generate a finite number of samples.
# DAQmx_Val_ContSamps = 10123 Acquire or generate samples until you stop the task.
# DAQmx_Val_HWTimedSinglePoint = 12522 Acquire or generate samples continuously using hardware timing without a buffer. Hardware timed single point sample mode is supported only for the sample clock and change detection timing types.
sample_per_Ch = ctypes.c_ulonglong(4)
sample_written = ctypes.c_ulonglong(10)
ch0_name = "DAQ6321/port0/line0"
ref_clock = " OnboardClock "
auto_start = ctypes.c_bool(0)
timeout = ctypes.c_double(10)

a = (ctypes.c_uint8 * 4)
data_array = a(255, 0, 255, 0)
print(data_array)
flag_task_done = ctypes.c_bool(0)

name = ctypes.c_wchar()
daq_mx_dll.DAQmxCreateTask("j", ctypes.byref(task_handle))
daq_mx_dll.DAQmxGetTaskName(task_handle, ctypes.byref(name),
                            ctypes.c_uint32(32))
print('task name ', name)

daq_mx_dll.DAQmxCreateDOChan(task_handle, ch0_name.encode('utf-8'), "",
                             line_grouping)
daq_mx_dll.DAQmxCfgSampClkTiming(task_handle, ref_clock.encode('utf-8'),
                                 sample_rate, active_edge, sample_mode,
                                 sample_per_Ch)
daq_mx_dll.DAQmxWriteDigitalU8(
    task_handle,
    sample_per_Ch,
    auto_start,
    timeout,
Ejemplo n.º 31
0
            return cls(obj.real, obj.imag)
        if isinstance(obj, (int, float)):
            return cls(obj.real, 0.0)
        raise NotImplementedError(repr(type(obj)))

    def topython(self):
        return complex(self.real, self.imag)


# Initialize type maps
_ctypes_imap = {
    ctypes.c_void_p: 'void*',
    None: 'void',
    ctypes.c_bool: 'bool',
    ctypes.c_char_p: 'char%s*' % (ctypes.sizeof(ctypes.c_char()) * 8),
    ctypes.c_wchar_p: 'char%s*' % (ctypes.sizeof(ctypes.c_wchar()) * 8),
}
_ctypes_char_map = {}
_ctypes_int_map = {}
_ctypes_uint_map = {}
_ctypes_float_map = {}
_ctypes_complex_map = {}
for _k, _m, _lst in [
    ('char', _ctypes_char_map, ['c_char', 'c_wchar']),
    ('int', _ctypes_int_map, [
        'c_int8', 'c_int16', 'c_int32', 'c_int64', 'c_int', 'c_long',
        'c_longlong', 'c_byte', 'c_short', 'c_ssize_t'
    ]),
    ('uint', _ctypes_uint_map, [
        'c_uint8', 'c_uint16', 'c_uint32', 'c_uint64', 'c_uint', 'c_ulong',
        'c_ulonglong', 'c_ubyte', 'c_ushort', 'c_size_t'
Ejemplo n.º 32
0
def _scan2vkey(scan):
    return 0xff & ctypes.windll.user32.VkKeyScanW(ctypes.c_wchar("%c" % scan))
Ejemplo n.º 33
0
def write_u_short(hProcess, address, value):
    ctypes.windll.kernel32.WriteProcessMemory(
        hProcess, address, ctypes.c_ushort(ctypes.c_wchar(value)),
        ctypes.sizeof(ctypes.c_ushort(value)), ctypes.c_ulong(0))
Ejemplo n.º 34
0
# numeric and mathematical types (CH 9)
a["DecimalType"] = decimal.Decimal(1)
a["CountType"] = itertools.count(0)
# data compression and archiving (CH 12)
a["TarInfoType"] = tarfile.TarInfo()
# generic operating system services (CH 15)
a["LoggerType"] = logging.getLogger()
a["FormatterType"] = logging.Formatter()  # pickle ok
a["FilterType"] = logging.Filter()  # pickle ok
a["LogRecordType"] = logging.makeLogRecord(_dict)  # pickle ok
a["OptionParserType"] = _oparser = optparse.OptionParser()  # pickle ok
a["OptionGroupType"] = optparse.OptionGroup(_oparser, "foo")  # pickle ok
a["OptionType"] = optparse.Option("--foo")  # pickle ok
if HAS_CTYPES:
    a["CCharType"] = _cchar = ctypes.c_char()
    a["CWCharType"] = ctypes.c_wchar()  # fail == 2.6
    a["CByteType"] = ctypes.c_byte()
    a["CUByteType"] = ctypes.c_ubyte()
    a["CShortType"] = ctypes.c_short()
    a["CUShortType"] = ctypes.c_ushort()
    a["CIntType"] = ctypes.c_int()
    a["CUIntType"] = ctypes.c_uint()
    a["CLongType"] = ctypes.c_long()
    a["CULongType"] = ctypes.c_ulong()
    a["CLongLongType"] = ctypes.c_longlong()
    a["CULongLongType"] = ctypes.c_ulonglong()
    a["CFloatType"] = ctypes.c_float()
    a["CDoubleType"] = ctypes.c_double()
    a["CSizeTType"] = ctypes.c_size_t()
    a["CLibraryLoaderType"] = ctypes.cdll
    a["StructureType"] = _Struct
Ejemplo n.º 35
0
# -*- coding: utf-8 -*-

from tools.factories import generator_factory
import ctypes

basic_cases = [
    [b'%C\n', ctypes.c_wchar(u'\u262D')],
    [b'% C\n', ctypes.c_wchar(u'\u262D')],
    [b'%+C\n', ctypes.c_wchar(u'\u262D')],
    [b'%#C\n', ctypes.c_wchar(u'\u262D')],
    [b'%0C\n', ctypes.c_wchar(u'\u262D')],
    [b'%-C\n', ctypes.c_wchar(u'\u262D')],
    [b'%10C\n', ctypes.c_wchar(u'\u262D')],
    [b'%.5C\n', ctypes.c_wchar(u'\u262D')],
    [b'%hhC\n', ctypes.c_wchar(u'\u262D')],
    [b'%llC\n', ctypes.c_wchar(u'\u262D')],
    [b'%hC\n', ctypes.c_wchar(u'\u262D')],
    [b'%lC\n', ctypes.c_wchar(u'\u262D')],
    [b'%jC\n', ctypes.c_wchar(u'\u262D')],
    [b'%zC\n', ctypes.c_wchar(u'\u262D')],
    [b'%C\n', ctypes.c_wchar('a')],
    [b'% C\n', ctypes.c_wchar('a')],
    [b'%+C\n', ctypes.c_wchar('a')],
    [b'%#C\n', ctypes.c_wchar('a')],
    [b'%0C\n', ctypes.c_wchar('a')],
    [b'%-C\n', ctypes.c_wchar('a')],
    [b'%10C\n', ctypes.c_wchar('a')],
    [b'%.5C\n', ctypes.c_wchar('a')],
    [b'%hhC\n', ctypes.c_wchar('a')],
    [b'%llC\n', ctypes.c_wchar('a')],
    [b'%hC\n', ctypes.c_wchar('a')],
Ejemplo n.º 36
0
    d.msg += '<arg ' + get_arg_xml(v) + '></arg>'
    v = ctypes.c_double(0x0E)
    d.msg += '<arg ' + get_arg_xml(v) + '></arg>'
    v = ctypes.c_longdouble(0x0F)
    d.msg += '<arg ' + get_arg_xml(v) + '></arg>'
    v = ctypes.c_longlong(0x10)
    d.msg += '<arg ' + get_arg_xml(v) + '></arg>'
    v = ctypes.c_ulonglong(0x11)
    d.msg += '<arg ' + get_arg_xml(v) + '></arg>'
    v = ctypes.c_ubyte(0x12)
    d.msg += '<arg ' + get_arg_xml(v) + '></arg>'
    v = ctypes.c_byte(0x13)
    d.msg += '<arg ' + get_arg_xml(v) + '></arg>'
    v = ctypes.c_char('a')
    d.msg += '<arg ' + get_arg_xml(v) + '></arg>'
    v = ctypes.c_wchar(u'b')
    d.msg += '<arg ' + get_arg_xml(v) + '></arg>'

    d.msg += '<arg ' + get_arg_xml("string test") + '></arg>'
    d.msg += '<arg ' + get_arg_xml(u"unicode test") + '></arg>'

    s = ctypes.c_char_p('testing c_char_p')
    d.msg += '<arg ' + get_arg_xml(s) + '></arg>'
    v = ctypes.cast(s, ctypes.c_void_p)
    d.msg += '<arg ' + get_arg_xml(v) + '></arg>'
    v = ctypes.c_void_p(0x1234)
    d.msg += '<arg ' + get_arg_xml(v) + '></arg>'
    v = EfiPy.EFI_HANDLE()
    d.msg += '<arg ' + get_arg_xml(v) + '></arg>'
    v = ctypes.c_void_p(0x00)
    d.msg += '<arg ' + get_arg_xml(v) + '></arg>'
Ejemplo n.º 37
0
    def render(self, text):
        
        ch = ctypes.c_wchar(text)

        # Layout rectangle; not clipped against so not terribly important.
        width = 10000
        height = self._bitmap_height
        rect = Rectf(0, self._bitmap_height 
                        - self.font.ascent + self.font.descent, 
                     width, height)

        # Set up GenericTypographic with 1 character measure range
        generic = ctypes.c_void_p()
        gdiplus.GdipStringFormatGetGenericTypographic(ctypes.byref(generic))
        format = ctypes.c_void_p()
        gdiplus.GdipCloneStringFormat(generic, ctypes.byref(format))

        # Measure advance
        bbox = Rectf()
        flags = (StringFormatFlagsMeasureTrailingSpaces | 
                 StringFormatFlagsNoClip | 
                 StringFormatFlagsNoFitBlackBox)
        gdiplus.GdipSetStringFormatFlags(format, flags)
        gdiplus.GdipMeasureString(self._graphics, ctypes.byref(ch), 1,
            self.font._gdipfont, ctypes.byref(rect), format,
            ctypes.byref(bbox), 0, 0)

        lsb = 0
        advance = int(math.ceil(bbox.width))

        # XXX HACK HACK HACK
        # Windows GDI+ is a filthy broken toy.  No way to measure the bounding
        # box of a string, or to obtain LSB.  What a joke.
        # 
        # For historical note, GDI cannot be used because it cannot composite
        # into a bitmap with alpha.
        #
        # It looks like MS have abandoned GDI and GDI+ and are finally
        # supporting accurate text measurement with alpha composition in .NET
        # 2.0 (WinForms) via the TextRenderer class; this has no C interface
        # though, so we're entirely screwed.
        # 
        # So anyway, this hack bumps up the width if the font is italic;
        # this compensates for some common fonts.  It's also a stupid waste of
        # texture memory.
    
        width = advance
        if self.font.italic:
            width += width // 2
        
        # XXX END HACK HACK HACK

        # Draw character to bitmap
        
        gdiplus.GdipGraphicsClear(self._graphics, 0x00000000)
        gdiplus.GdipDrawString(self._graphics, ctypes.byref(ch), 1,
            self.font._gdipfont, ctypes.byref(rect), format,
            self._brush)
        gdiplus.GdipFlush(self._graphics, 1)

        bitmap_data = BitmapData()
        gdiplus.GdipBitmapLockBits(self._bitmap, 
            byref(self._rect), ImageLockModeRead, self._format, 
            byref(bitmap_data))
        
        # Create buffer for RawImage
        buffer = create_string_buffer(
            bitmap_data.Stride * bitmap_data.Height)
        memmove(buffer, bitmap_data.Scan0, len(buffer))
        
        # Unlock data
        gdiplus.GdipBitmapUnlockBits(self._bitmap, byref(bitmap_data))
        
        image = pyglet.image.ImageData(width, height, 
            'BGRA', buffer, -bitmap_data.Stride)

        glyph = self.font.create_glyph(image)
        glyph.set_bearings(-self.font.descent, lsb, advance)

        return glyph
Ejemplo n.º 38
0
def main():
    diff = difflib.Differ()
    iocla_printf = ctypes.CDLL('./libprint.so').iocla_printf
    libc = ctypes.CDLL('libc.so.6')
    data_type_regex = re.compile('%?%[duxcs]')
    c_data_type = {
        '%d': lambda x: ctypes.c_int32(int(x)),
        '%u': lambda x: ctypes.c_uint32(int(x)),
        '%x': lambda x: ctypes.c_uint32(int(x)),
        '%c': lambda x: ctypes.c_wchar(string_escape(x)),
        '%s': lambda x: str.encode(string_escape(x))
    }

    if not os.path.exists(OUT_DIR):
        os.makedirs(OUT_DIR)

    print(25 * '=' + ' Tema 1 IOCLA ' + '=' * 25 + '\n')  # Total = 64

    for test_no in range(NUM_TESTS):
        with open(f'input/test{test_no}') as test:
            description, *print_params = test.read().split('\n')
            fmt, *args = print_params
            for idx, identifier in enumerate(re.findall(data_type_regex, fmt)):
                if identifier.startswith('%%'):
                    continue
                args[idx] = c_data_type[identifier](args[idx])
            fmt = str.encode(string_escape(fmt))

            sys_stdout = os.dup(sys.stdout.fileno())

            iocla_fd = os.open(f'{OUT_DIR}/test{test_no}.out',
                               os.O_WRONLY | os.O_CREAT | os.O_TRUNC)
            os.dup2(iocla_fd, sys.stdout.fileno())
            iocla_printf_ret = iocla_printf(fmt, *args)
            libc.fflush(None)
            os.close(iocla_fd)

            libc_fd = os.open(f'{OUT_DIR}/test{test_no}.ref',
                              os.O_WRONLY | os.O_CREAT | os.O_TRUNC)
            os.dup2(libc_fd, sys.stdout.fileno())
            libc_printf_ret = libc.printf(fmt, *args)
            libc.fflush(None)
            os.close(libc_fd)

            os.dup2(sys_stdout, sys.stdout.fileno())

            iocla_out = open(f'{OUT_DIR}/test{test_no}.out', 'r').read()
            libc_out = open(f'{OUT_DIR}/test{test_no}.ref', 'r').read()
            diff = list(difflib.unified_diff(iocla_out, libc_out))

            print(f'{test_no} {description} ' +
                  (55 - len(description) - test_no // 10) * '.',
                  end=' ')
            if len(diff) == 0:
                if iocla_printf_ret != libc_printf_ret:
                    print(' FAIL')
                    print(
                        f'Your print returned {iocla_printf_ret} instead of {libc_printf_ret}'
                    )
                else:
                    print(' PASS')
                    global PASS_TESTS
                    PASS_TESTS = PASS_TESTS + 1
            else:
                print(' FAIL')
                # print('\n'.join(diff))

            os.close(sys_stdout)

    print(f'\nTotal: {PASS_TESTS / NUM_TESTS * 100:.2f}')
Ejemplo n.º 39
0
# numeric and mathematical types (CH 9)
a['DecimalType'] = decimal.Decimal(1)
a['CountType'] = itertools.count(0)
# data compression and archiving (CH 12)
a['TarInfoType'] = tarfile.TarInfo()
# generic operating system services (CH 15)
a['LoggerType'] = logging.getLogger()
a['FormatterType'] = logging.Formatter()  # pickle ok
a['FilterType'] = logging.Filter()  # pickle ok
a['LogRecordType'] = logging.makeLogRecord(_dict)  # pickle ok
a['OptionParserType'] = _oparser = optparse.OptionParser()  # pickle ok
a['OptionGroupType'] = optparse.OptionGroup(_oparser, "foo")  # pickle ok
a['OptionType'] = optparse.Option('--foo')  # pickle ok
if HAS_CTYPES:
    a['CCharType'] = _cchar = ctypes.c_char()
    a['CWCharType'] = ctypes.c_wchar()  # fail == 2.6
    a['CByteType'] = ctypes.c_byte()
    a['CUByteType'] = ctypes.c_ubyte()
    a['CShortType'] = ctypes.c_short()
    a['CUShortType'] = ctypes.c_ushort()
    a['CIntType'] = ctypes.c_int()
    a['CUIntType'] = ctypes.c_uint()
    a['CLongType'] = ctypes.c_long()
    a['CULongType'] = ctypes.c_ulong()
    a['CLongLongType'] = ctypes.c_longlong()
    a['CULongLongType'] = ctypes.c_ulonglong()
    a['CFloatType'] = ctypes.c_float()
    a['CDoubleType'] = ctypes.c_double()
    a['CSizeTType'] = ctypes.c_size_t()
    a['CLibraryLoaderType'] = ctypes.cdll
    a['StructureType'] = _Struct
Ejemplo n.º 40
0
    def test05_ctypes_as_ref_and_ptr(self):
        """Use ctypes for pass-by-ref/ptr"""

        # See:
        #  https://docs.python.org/2/library/ctypes.html#fundamental-data-types
        #
        # ctypes type       C type                                      Python type
        # ------------------------------------------------------------------------------
        # c_bool            _Bool                                       bool (1)
        #
        # c_char            char 1-character                            string
        # c_wchar           wchar_t 1-character                         unicode string
        # c_byte            char                                        int/long
        # c_ubyte           unsigned char                               int/long
        #
        # c_short           short                                       int/long
        # c_ushort          unsigned short                              int/long
        # c_int             int                                         int/long
        # c_uint            unsigned int                                int/long
        # c_long            long                                        int/long
        # c_ulong           unsigned long                               int/long
        # c_longlong        __int64 or long long                        int/long
        # c_ulonglong       unsigned __int64 or unsigned long long      int/long
        #
        # c_float           float                                       float
        # c_double          double                                      float
        # c_longdouble      long double                                 float

        import cppyy, ctypes

        ctd = cppyy.gbl.CppyyTestData()

        ### pass by reference/pointer and set value back

        for e in ['_r', '_p']:
            # boolean type
            b = ctypes.c_bool(False)
            getattr(ctd, 'set_bool' + e)(b)
            assert b.value == True

            # char types
            if e == '_r':
                c = ctypes.c_char(b'\0')
                getattr(ctd, 'set_char' + e)(c)
                assert c.value == b'a'
                c = ctypes.c_wchar(u'\0')
                getattr(ctd, 'set_wchar' + e)(c)
                assert c.value == u'b'
                c = ctypes.c_byte(0)
                getattr(ctd, 'set_schar' + e)(c)
                assert c.value == ord('c')
            c = ctypes.c_ubyte(0)
            getattr(ctd, 'set_uchar' + e)(c)
            assert c.value == ord('d')

            # integer types
            i = ctypes.c_short(0)
            getattr(ctd, 'set_short' + e)(i)
            assert i.value == -1
            i = ctypes.c_ushort(0)
            getattr(ctd, 'set_ushort' + e)(i)
            assert i.value == 2
            i = ctypes.c_int(0)
            getattr(ctd, 'set_int' + e)(i)
            assert i.value == -3
            i = ctypes.c_uint(0)
            getattr(ctd, 'set_uint' + e)(i)
            assert i.value == 4
            i = ctypes.c_long(0)
            getattr(ctd, 'set_long' + e)(i)
            assert i.value == -5
            i = ctypes.c_ulong(0)
            getattr(ctd, 'set_ulong' + e)(i)
            assert i.value == 6
            i = ctypes.c_longlong(0)
            getattr(ctd, 'set_llong' + e)(i)
            assert i.value == -7
            i = ctypes.c_ulonglong(0)
            getattr(ctd, 'set_ullong' + e)(i)
            assert i.value == 8

            # floating point types
            f = ctypes.c_float(0)
            getattr(ctd, 'set_float' + e)(f)
            assert f.value == 5.
            f = ctypes.c_double(0)
            getattr(ctd, 'set_double' + e)(f)
            assert f.value == -5.
            f = ctypes.c_longdouble(0)
            getattr(ctd, 'set_ldouble' + e)(f)
            assert f.value == 10.

    ### pass by pointer and set value back, now using byref (not recommended)

        cb = ctypes.byref

        # boolean type
        b = ctypes.c_bool(False)
        ctd.set_bool_p(cb(b))
        assert b.value == True

        # char types
        c = ctypes.c_ubyte(0)
        ctd.set_uchar_p(cb(c))
        assert c.value == ord('d')

        # integer types
        i = ctypes.c_short(0)
        ctd.set_short_p(cb(i))
        assert i.value == -1
        i = ctypes.c_ushort(0)
        ctd.set_ushort_p(cb(i))
        assert i.value == 2
        i = ctypes.c_int(0)
        ctd.set_int_p(cb(i))
        assert i.value == -3
        i = ctypes.c_uint(0)
        ctd.set_uint_p(cb(i))
        assert i.value == 4
        i = ctypes.c_long(0)
        ctd.set_long_p(cb(i))
        assert i.value == -5
        i = ctypes.c_ulong(0)
        ctd.set_ulong_p(cb(i))
        assert i.value == 6
        i = ctypes.c_longlong(0)
        ctd.set_llong_p(cb(i))
        assert i.value == -7
        i = ctypes.c_ulonglong(0)
        ctd.set_ullong_p(cb(i))
        assert i.value == 8

        # floating point types
        f = ctypes.c_float(0)
        ctd.set_float_p(cb(f))
        assert f.value == 5.
        f = ctypes.c_double(0)
        ctd.set_double_p(cb(f))
        assert f.value == -5.

        ### pass by ptr/ptr with allocation (ptr/ptr is ambiguous in it's task, so many
        # types are allowed to pass; this tests allocation into the pointer)

        from ctypes import POINTER

        # boolean type
        b = POINTER(ctypes.c_bool)()
        ctd.set_bool_ppa(b)
        assert b[0] == True
        assert b[1] == False
        assert b[2] == True
        cppyy.ll.array_delete(b)

        # char types
        c = POINTER(ctypes.c_ubyte)()
        ctd.set_uchar_ppa(c)
        assert c[0] == ord('k')
        assert c[1] == ord('l')
        assert c[2] == ord('m')
        cppyy.ll.array_delete(c)

        # integer types
        i = POINTER(ctypes.c_short)()
        ctd.set_short_ppa(i)
        assert i[0] == -1
        assert i[1] == -2
        assert i[2] == -3
        cppyy.ll.array_delete(i)
        i = POINTER(ctypes.c_ushort)()
        ctd.set_ushort_ppa(i)
        assert i[0] == 4
        assert i[1] == 5
        assert i[2] == 6
        cppyy.ll.array_delete(i)
        i = POINTER(ctypes.c_int)()
        ctd.set_int_ppa(i)
        assert i[0] == -7
        assert i[1] == -8
        assert i[2] == -9
        cppyy.ll.array_delete(i)
        i = POINTER(ctypes.c_uint)()
        ctd.set_uint_ppa(i)
        assert i[0] == 10
        assert i[1] == 11
        assert i[2] == 12
        cppyy.ll.array_delete(i)
        i = POINTER(ctypes.c_long)()
        ctd.set_long_ppa(i)
        assert i[0] == -13
        assert i[1] == -14
        assert i[2] == -15
        cppyy.ll.array_delete(i)
        i = POINTER(ctypes.c_ulong)()
        ctd.set_ulong_ppa(i)
        assert i[0] == 16
        assert i[1] == 17
        assert i[2] == 18
        cppyy.ll.array_delete(i)
        i = POINTER(ctypes.c_longlong)()
        ctd.set_llong_ppa(i)
        assert i[0] == -19
        assert i[1] == -20
        assert i[2] == -21
        cppyy.ll.array_delete(i)
        i = POINTER(ctypes.c_ulonglong)()
        ctd.set_ullong_ppa(i)
        assert i[0] == 22
        assert i[1] == 23
        assert i[2] == 24
        cppyy.ll.array_delete(i)

        # floating point types
        f = POINTER(ctypes.c_float)()
        ctd.set_float_ppa(f)
        assert f[0] == 5
        assert f[1] == 10
        assert f[2] == 20
        cppyy.ll.array_delete(f)
        f = POINTER(ctypes.c_double)()
        ctd.set_double_ppa(f)
        assert f[0] == -5
        assert f[1] == -10
        assert f[2] == -20
        cppyy.ll.array_delete(f)
        f = POINTER(ctypes.c_longdouble)()
        ctd.set_ldouble_ppa(f)
        assert f[0] == 5
        assert f[1] == 10
        assert f[2] == 20
        cppyy.ll.array_delete(f)