关于 ctypes 的简单用例

###结构体、数组、指针、指向数组的指针

from ctypes import *

class point(Structure):
    pass

point._fields_ = [
    ('x', c_int),
    ('y', c_int)
]

arry_gen = point * 10
arry = arry_gen(range(10))

arry_ptr_gen = POINTER(point)
arry_ptr = arry_ptr_gen(arry)

###回调函数用法

# /* demo.c --> demo.so */
# include <stdio.h>

# typedef int (*callback)(void);

# int func_arg (callback get_value)
# {
#     return get_value();
# }
from ctypes import *

def getvalue():
    return 10

def run():
    libdemo = cdll.LoadLibrary('./demo.so')
    func_arg = libdemo.func_arg
    func_arg.restype = c_int

    py_func_getvalue = CFUNCTYPE(c_void_p)
    func_getvalue = py_func_getvalue(getvalue)
    print func_arg(func_getvalue)
run()

###根据内存地址获取数据,不过,尽量少用,这种方法并不很好

memaddr = libc.xxx()
v = c_char_p(memaddr).value