Example #1
0
def _cast_ptr2(x, _type):
    if isinstance(x, ffi.CData):
        if (_type.item == ffi.typeof(x) or
            (_type.item.cname == 'void' and ffi.typeof(x).kind in
             ['struct', 'union'])):
            return ffi.addressof(x), x
        return x, x

    if isinstance(x, _collections.Iterable):
        if _type.item.kind == 'pointer':
            ptrs = [_cast_ptr(i, _type.item) for i in x]
            ret = ffi.new(_type.item.cname+'[]', [i for i, _ in ptrs])
            _weakkey_dict[ret] = tuple(i for _, i in ptrs if i != ffi.NULL)
        else:
            ret = ffi.new(_type.item.cname+'[]', x)

        return ret, ret

    return ffi.cast(_type, x), x
Example #2
0
def _new(ctype, **kwargs):
    _type = ffi.typeof(ctype)

    # keep only valued kwargs
    kwargs = {k: kwargs[k] for k in kwargs if kwargs[k]}

    # cast pointer
    ptrs = {}
    pfns = {}
    pcs = {}
    for k, v in kwargs.items():
        # convert tuple pair to dict
        ktype = dict(_type.fields)[k].type

        if k == 'pCode':
            pcs[k] = ffi.cast('uint32_t*', ffi.from_buffer(v))
        elif k.startswith('pfn'):
            pfn_name = _get_pfn_name(ctype)
            mod = sys.modules[__name__]
            setattr(mod, '_internal_' + pfn_name, v)
            pfns[k] = getattr(mod, '_external_' + pfn_name)
        elif ktype.kind == 'pointer':
            ptrs[k] = _cast_ptr(v, ktype)

    # init object
    init = dict(kwargs,  **{k: v for k, (v, _) in ptrs.items()})
    init.update(pfns)
    init.update(pcs)

    ret = ffi.new(_type.cname + '*', init)[0]