Python을 쓰다보면 간혹 Windows API를 사용해야 할 때가 있다.
필자의 경우에도 Python으로 열심히 짜놓은 파서가 받는 인풋 값중 하나가 Python에서 지원하지 않는 FILETIME형태를 만난 적이 있다.
물론 변환 코드를 직접 작성하는 방법도 있지만, 이왕이면 MS에서 제공하는 안전한 함수를 사용하는 것이 좋다.
이에 kernel32.dll을 직접 로드해서 API를 사용하는 방법을 통해 문제를 해결하였다.
이 방법은 Visual C++에서 Windows API의 GetProcAddress()함수를 통해 Undocumented Function을 사용하는 것과 비슷한 방법이다.
필자가 작성한 FILETIME to SYSTEMTIME은 아래와 같다.
1: from ctypes import windll, Structure, byref, GetLastError, WinError, c_ulong, c_ushort2:3: //load to kernel32.dll4: kernel32 = windll.kernel325:6: // type define7: WORD = c_ushort8: DWORD = c_ulong9:10: // 구조체를 정의11: class FILETIME(Structure):12: _fields_ = [("dwLowDateTime", DWORD),13: ("dwHighDateTime", DWORD)]14:15: class SYSTEMTIME(Structure):16: _fields_ = [("wYear", WORD),17: ("wMonth", WORD),18: ("wDayofWeek", WORD),19: ("wDay", WORD),20: ("wHour", WORD),21: ("wMinute", WORD),22: ("wSecond", WORD),23: ("wMilliseconds", WORD)24: ]25:26: def FILETIME_Parser():27: filetime = FILETIME() // FILETIME구조체 생성28: filetime.dwHighDateTime = int(time_string.split(',')[1]) // ,를 구분자29: filetime.dwLowDateTime = int(time_string.split(',')[1])30: systemtime = SYSTEMTIME()31: kernel32.FileTimeToSystemTime(byref(filetime), byref(systemtime))32: result_time = "%d-%d-%d %d:%d:%d"%(systemtime.wYear, systemtime.wMonth,\
33: systemtime.wDay, systemtime.wHour, systemtime.wMinute, systemtime.wSecond)34: return result_time
31행을 보면, kernel32.dll 내부의 FileTImeToSystemTime API를 사용한 것을 확인할 수 있다.
python은 본래 call by value를 기본으로 동작되기 때문에 ctype클래스의 method인 byref를 활용하여 FILETIME, SYSTEMTIME구조체의 주소값을 넘겨주었다.
이 방법을 통하여 다른 dll의 함수도 python에서 쉽게 사용할 수 있다. :)
태그 : python



최근 덧글