Python ctypes


 - ctypes.POINTER(type)

> This factory function creates and returns a new ctypes pointer type.
> Pointer types are cached an reused internally, so calling this
> function repeatedly is cheap. type must be a ctypes type.

 - ctypes.pointer(obj)

> This function creates a new pointer instance, pointing to obj. The
> returned object is of the type POINTER(type(obj)).
> 
> Note: If you just want to pass a pointer to an object to a foreign
> function call, you should use byref(obj) which is much faster.

 - ctypes.cast(obj, type)

> This function is similar to the cast operator in C. It returns a new
> instance of type which points to the same memory block as obj. type
> must be a pointer type, and obj must be an object that can be
> interpreted as a pointer.


应用:

def string2struct(string, stype):
    # convert python string to c/c++ structure type
    if not issubclass(stype, Structure):
        raise ValueError('The type of the struct is not a ctypes.Structure')
    p = cast(string, POINTER(stype))
    return p.contents

def struct2string(s):
    length = sizeof(s)
    p = cast(pointer(s), POINTER(c_char * length))
    return p.contents.raw

你可能感兴趣的:(Python ctypes)