import ctypes, os# Try to locate the .so file in the same directory as this file_file ='libsample.so'_path = os.path.join(*(os.path.split(__file__)[:-1]+(_file,)))_mod = ctypes.cdll.LoadLibrary(_path)# int gcd(int, int)gcd = _mod.gcdgcd.argtypes =(ctypes.c_int, ctypes.c_int)gcd.restype = ctypes.c_int# int in_mandel(double, double, int)in_mandel = _mod.in_mandelin_mandel.argtypes =(ctypes.c_double, ctypes.c_double, ctypes.c_int)in_mandel.restype = ctypes.c_int# int divide(int, int, int *)_divide = _mod.divide_divide.argtypes =(ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_int))_divide.restype = ctypes.c_intdefdivide(x,y): rem = ctypes.c_int() quot =_divide(x, y, rem)return quot,rem.value# void avg(double *, int n)# Define a special type for the 'double *' argumentclassDoubleArrayType:deffrom_param(self,param): typename =type(param).__name__ifhasattr(self,'from_'+ typename):returngetattr(self,'from_'+ typename)(param)elifisinstance(param, ctypes.Array):return paramelse:raiseTypeError("Can't convert %s"% typename)# Cast from array.array objectsdeffrom_array(self,param):if param.typecode !='d':raiseTypeError('must be an array of doubles') ptr, _ = param.buffer_info()return ctypes.cast(ptr, ctypes.POINTER(ctypes.c_double))# Cast from lists/tuplesdeffrom_list(self,param): val =((ctypes.c_double)*len(param))(*param)return val from_tuple = from_list# Cast from a numpy arraydeffrom_ndarray(self,param):return param.ctypes.data_as(ctypes.POINTER(ctypes.c_double))DoubleArray =DoubleArrayType()_avg = _mod.avg_avg.argtypes =(DoubleArray, ctypes.c_int)_avg.restype = ctypes.c_doubledefavg(values):return_avg(values, len(values))# struct Point { }classPoint(ctypes.Structure): _fields_ =[('x', ctypes.c_double),('y', ctypes.c_double)]# double distance(Point *, Point *)distance = _mod.distancedistance.argtypes =(ctypes.POINTER(Point), ctypes.POINTER(Point))distance.restype = ctypes.c_double