(INTERNAL) New ctypes function binding.
168683
def _Cfunction(name, flags, errcheck, *types):
    
    if hasattr(dll, name) and name in _Globals:
        p = ctypes.CFUNCTYPE(*types)
        f = p((name, dll), flags)
        if errcheck is not None:
            f.errcheck = errcheck
        # replace the Python function
        # in this module, but only when
        # running as python -O or -OO
        if __debug__:
            _Cfunctions[name] = f
        else:
            _Globals[name] = f
        return f
    raise NameError('no function %r' % (name,))
857719
def declare_units(out_units, **units_by_name):
    """"""

    def dec(func):
        # Match the signature of the function to the arguments given to the decorator
        sig = signature(func)
        bound_units = sig.bind_partial(**units_by_name)

        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            # Match all passed in value to their proper arguments so we can check units
            bound_args = sig.bind(*args, **kwargs)
            for name, val in bound_args.arguments.items():
                _check_units(val, bound_units.arguments.get(name, None))

            out = func(*args, **kwargs)

            # In the generic case, we use the default units that should have been propagated by the computation.
            if '[' in out_units:
                _check_units(out, out_units)

            # Otherwise, we specify explicitly the units.
            else:
                out.attrs['units'] = out_units
            return out

        return wrapper

    return dec
949040
def bind_type(python_value):
    """"""
    binding_table = {'bool': Bool, 'int': Int, 'float': Float}

    if python_value is None:
        return NoneType()

    python_type = type(python_value)

    gibica_type = binding_table.get(python_type.__name__)

    if gibica_type is None:
        raise TypeError('Impossible to recognize underlying type.')
    return gibica_type(python_value)
706078
def FUNCTION_DECL(self, cursor):
        """"""
        # FIXME to UT
        name = self.get_unique_name(cursor)
        if self.is_registered(name):
            return self.get_registered(name)
        returns = self.parse_cursor_type(cursor.type.get_result())
        attributes = []
        extern = False
        obj = typedesc.Function(name, returns, attributes, extern)
        for arg in cursor.get_arguments():
            arg_obj = self.parse_cursor(arg)
            # if arg_obj is None:
            #    code.interact(local=locals())
            obj.add_argument(arg_obj)
        # code.interact(local=locals())
        self.register(name, obj)
        self.set_location(obj, cursor)
        self.set_comment(obj, cursor)
        return obj
1211939
def _ctype_dict(param_dict):
    
    assert(isinstance(param_dict, dict)), \
        "unexpected type for param_dict: " + str(type(param_dict))
    c_keys = c_array(ctypes.c_char_p, [c_str(k) for k in param_dict.keys()])
    c_vals = c_array(ctypes.c_char_p, [c_str(str(v)) for v in param_dict.values()])
    return (c_keys, c_vals)
1035494
def ctypes2numpy(cptr, length, dtype):
    
    if not isinstance(cptr, ctypes.POINTER(ctypes.c_float)):
        raise RuntimeError('expected float pointer')
    res = np.zeros(length, dtype=dtype)
    if not ctypes.memmove(res.ctypes.data, cptr, length * res.strides[0]):
        raise RuntimeError('memmove failed')
    return res
889451
def _ctypes_ex_parameters(executable):
    
    result = []
    for p in executable.ordered_parameters:
        result.extend(p.ctypes_parameter())

    if type(executable).__name__ == "Function":
        result.extend(executable.ctypes_parameter()) #This method inherits from ValueElement.
        
    return result
1186939
def _wrap_type_instantiation(self, type_cls):
        """"""
        def wrapper(*args, **kwargs):
            # use args for struct arguments??
            return type_cls(stream=self._null_stream)
        return wrapper
1147776
def from_dict(cls, ctx):
        ''
        ctx = Context(ctx)
        s = cls()
        ContextFlags = ctx['ContextFlags']
        setattr(s, 'ContextFlags', ContextFlags)
        if (ContextFlags & CONTEXT_DEBUG_REGISTERS) == CONTEXT_DEBUG_REGISTERS:
            for key in s._ctx_debug:
                setattr(s, key, ctx[key])
        if (ContextFlags & CONTEXT_FLOATING_POINT) == CONTEXT_FLOATING_POINT:
            fsa = ctx['FloatSave']
            s.FloatSave = FLOATING_SAVE_AREA.from_dict(fsa)
        if (ContextFlags & CONTEXT_SEGMENTS) == CONTEXT_SEGMENTS:
            for key in s._ctx_segs:
                setattr(s, key, ctx[key])
        if (ContextFlags & CONTEXT_INTEGER) == CONTEXT_INTEGER:
            for key in s._ctx_int:
                setattr(s, key, ctx[key])
        if (ContextFlags & CONTEXT_CONTROL) == CONTEXT_CONTROL:
            for key in s._ctx_ctrl:
                setattr(s, key, ctx[key])
        if (ContextFlags & CONTEXT_EXTENDED_REGISTERS) == CONTEXT_EXTENDED_REGISTERS:
            er = ctx['ExtendedRegisters']
            for index in compat.xrange(0, MAXIMUM_SUPPORTED_EXTENSION):
                s.ExtendedRegisters[index] = er[index]
        return s
689657
def preprocessor(accepts, exports, flag=None):
    """"""
    def decorator(f):
        preprocessors.append((accepts, exports, flag, f))
        return f
    return decorator
560860
def _Cobject(cls, ctype):
    
    o = object.__new__(cls)
    o._as_parameter_ = ctype
    return o
8750
def execstr_funckw(func):
    
    import utool as ut
    funckw = ut.get_func_kwargs(func)
    return ut.execstr_dict(funckw, explicit=True)
666763
def asnumpy(self):
        """"""

        # Create C variables that will serve as out parameters for TCMPS.
        data_ptr = _ctypes.POINTER(_ctypes.c_float)()    # float* data_ptr
        shape_ptr = _ctypes.POINTER(_ctypes.c_size_t)()  # size_t* shape_ptr
        dim = _ctypes.c_size_t()                         # size_t dim

        # Obtain pointers into memory owned by the C++ object self.handle.
        # Note that this may trigger synchronization with another thread
        # producing the data.
        status_code = self._LIB.TCMPSReadFloatArray(
            self.handle, _ctypes.byref(data_ptr), _ctypes.byref(shape_ptr),
            _ctypes.byref(dim))
        assert status_code == 0, "Error calling TCMPSReadFloatArray"

        return _numpy_array_from_ctypes(data_ptr, shape_ptr, dim)
243301
def _init_torch_module():
    """"""
    plist = ctypes.POINTER(FunctionHandle)()
    size = ctypes.c_uint()
    check_call(_LIB.MXListFunctions(ctypes.byref(size),
                                    ctypes.byref(plist)))

    module_obj = sys.modules[__name__]
    for i in range(size.value):
        hdl = FunctionHandle(plist[i])
        function = _make_torch_function(hdl)
        # if function name starts with underscore, register as static method of NDArray
        if function is not None:
            setattr(module_obj, function.__name__, function)
1278451
def make_ctypes_convertor(self, _flags):
        
        tu = util.get_tu('''
typedef short short_t;
typedef int int_t;
typedef long long_t;
typedef long long longlong_t;
typedef float float_t;
typedef double double_t;
typedef long double longdouble_t;
typedef void* pointer_t;''', flags=_flags)
        size = util.get_cursor(tu, 'short_t').type.get_size() * 8
        self.ctypes_typename[TypeKind.SHORT] = 'c_int%d' % (size)
        self.ctypes_typename[TypeKind.USHORT] = 'c_uint%d' % (size)
        self.ctypes_sizes[TypeKind.SHORT] = size
        self.ctypes_sizes[TypeKind.USHORT] = size

        size = util.get_cursor(tu, 'int_t').type.get_size() * 8
        self.ctypes_typename[TypeKind.INT] = 'c_int%d' % (size)
        self.ctypes_typename[TypeKind.UINT] = 'c_uint%d' % (size)
        self.ctypes_sizes[TypeKind.INT] = size
        self.ctypes_sizes[TypeKind.UINT] = size

        size = util.get_cursor(tu, 'long_t').type.get_size() * 8
        self.ctypes_typename[TypeKind.LONG] = 'c_int%d' % (size)
        self.ctypes_typename[TypeKind.ULONG] = 'c_uint%d' % (size)
        self.ctypes_sizes[TypeKind.LONG] = size
        self.ctypes_sizes[TypeKind.ULONG] = size

        size = util.get_cursor(tu, 'longlong_t').type.get_size() * 8
        self.ctypes_typename[TypeKind.LONGLONG] = 'c_int%d' % (size)
        self.ctypes_typename[TypeKind.ULONGLONG] = 'c_uint%d' % (size)
        self.ctypes_sizes[TypeKind.LONGLONG] = size
        self.ctypes_sizes[TypeKind.ULONGLONG] = size

        # FIXME : Float && http://en.wikipedia.org/wiki/Long_double
        size0 = util.get_cursor(tu, 'float_t').type.get_size() * 8
        size1 = util.get_cursor(tu, 'double_t').type.get_size() * 8
        size2 = util.get_cursor(tu, 'longdouble_t').type.get_size() * 8
        # 2014-01 stop generating crap.
        # 2015-01 reverse until better solution is found
        # the idea is that a you cannot assume a c_double will be same format as a c_long_double.
        # at least this pass size TU
        if size1 != size2:
            self.ctypes_typename[TypeKind.LONGDOUBLE] = 'c_long_double_t'
        else:
            self.ctypes_typename[TypeKind.LONGDOUBLE] = 'c_double'

        self.ctypes_sizes[TypeKind.FLOAT] = size0
        self.ctypes_sizes[TypeKind.DOUBLE] = size1
        self.ctypes_sizes[TypeKind.LONGDOUBLE] = size2

        # save the target pointer size.
        size = util.get_cursor(tu, 'pointer_t').type.get_size() * 8
        self.ctypes_sizes[TypeKind.POINTER] = size
        self.ctypes_sizes[TypeKind.NULLPTR] = size

        log.debug('ARCH sizes: long:%s longdouble:%s',
                  self.ctypes_typename[TypeKind.LONG],
                  self.ctypes_typename[TypeKind.LONGDOUBLE])
        return
935654
def initialized(func):
    

    def wrapper(self, *args, **kwargs):
        """ internal wrapper function """
        if not self.__is_initialized__:
            return EmptyDot()
        return func(self, *args, **kwargs)
    return wrapper
497115
def cast(cast_fn):
    

    def inner(func):
        def call(*args, **kwargs):
            return cast_fn(func(*args, **kwargs))

        functools.update_wrapper(call, func)
        return call

    return inner