티스토리 뷰


# First of all, need to read python doc. about ctypes..
from ctypes import *


class Obj(Structure) :
    _fields_ = [("name", c_char_p), ("id", c_int)]


class Person(Structure) :
    _fields_ = [("stInfo", Obj)]
    
    def __init__(self, person=None):
        self.stInfo = Obj()
        if person is not None :
            self.stInfo = person.stInfo

    def __str__(self) :
        return "I'm %s, and my id is %d" % (self.stInfo.name, self.stInfo.id)



qsort = cdll.msvcrt.qsort

def cmpFunc(a, b) : # a, b are POINTER(Person) type
    return a.contents.stInfo.id - b.contents.stInfo.id
    # (*Person).stInfo.id - (*Person).stInfo.id in C

CmpFuncType = CFUNCTYPE(c_int, POINTER(Person), POINTER(Person))



if "__main__" == __name__ :

    # Virtual process converting data from DB to Python
    p1 = Person()
    p2 = Person()
    p3 = Person()

    p1.stInfo.name = "David"
    p1.stInfo.id = 2342

    p2.stInfo.name = "Tom"
    p2.stInfo.id = 4233

    p3.stInfo.name = "Sarah"
    p3.stInfo.id = 1243

    numPeople = 3 # retrieved number from DB

    # Python only from now on
    people = (Person*numPeople)()
    people[0] = p1 #Person(p1)
    people[1] = p2 #Person(p2)
    people[2] = p3 #Person(p3)


    for i, p in enumerate(people) :
        print("i :" + str(p))
    
    qsort(byref(people), numPeople, sizeof(Person), CmpFuncType(cmpFunc))
    print("\n\nAfter qsort with id...\n\n")

    for i, p in enumerate(people) :
        print("i :" + str(p))
댓글