단디연구소

[Python] Ctypes 모듈 본문

연구 자료/Programming

[Python] Ctypes 모듈

단디연구소 2016. 2. 11. 13:46

윈도우 API를 이용할 일이 많은데 파이썬에서 ctypes라는 모듈이 있다는것을 알앗다. 


이 모듈은 dll의 함수를 호출 가능 하게 하고 c 데이터 타입을 사용할수 있다.


https://docs.python.org/2/library/ctypes.html


# ctypes 형태의 타입을 마이크로소프트 타입으로 매핑

from ctypes import *


BYTE      = c_ubyte

WORD      = c_ushort

DWORD     = c_ulong

LONG      = c_ulong

LPBYTE    = POINTER(c_ubyte)

LPTSTR    = POINTER(c_char) 

HANDLE    = c_void_p

PVOID     = c_void_p

LPVOID    = c_void_p

UINT_PTR  = c_ulong

SIZE_T    = c_ulong

HMODULE   = c_void_p

NULL      = c_int(0)


# 구조체 선언 

class STARTUPINFO(Structure):

    _fields_ = [

        ("cb",            DWORD),        

        ("lpReserved",    LPTSTR), 

        ("lpDesktop",     LPTSTR),  

        ("lpTitle",       LPTSTR),

        ("dwX",           DWORD),

        ("dwY",           DWORD),

        ("dwXSize",       DWORD),

        ("dwYSize",       DWORD),

        ("dwXCountChars", DWORD),

        ("dwYCountChars", DWORD),

        ("dwFillAttribute",DWORD),

        ("dwFlags",       DWORD),

        ("wShowWindow",   WORD),

        ("cbReserved2",   WORD),

        ("lpReserved2",   LPBYTE),

        ("hStdInput",     HANDLE),

        ("hStdOutput",    HANDLE),

        ("hStdError",     HANDLE),

        ]


class PROCESS_INFORMATION(Structure):

    _fields_ = [

        ("hProcess",    HANDLE),

        ("hThread",     HANDLE),

        ("dwProcessId", DWORD),

        ("dwThreadId",  DWORD),

        ]


# API호출(실행)

from ctypes import *


KERNEL32 = windll.kernel32

CREATE_NEW_CONSOLE        = 0x00000010


def CreateProcess(path):


    startup_info = STARTUPINFO()

    startup_info.cb = sizeof(startup_info)

    process_info = PROCESS_INFORMATION()

    creation_flags = CREATE_NEW_CONSOLE


    created = KERNEL32.CreateProcessA(path,

                                          None,

                                          None,

                                          None,

                                          None,

                                          creation_flags,

                                          None,

                                          None,

                                          byref(startup_info),

                                          byref(process_info))


    if created:

        pid = process_info.dwProcessId

        return True

    else:

        return False




'연구 자료 > Programming' 카테고리의 다른 글

[Python] PE파일 32bit, 64bit구분하기  (0) 2016.04.18
[python] gmail smtp 메일 전송  (0) 2016.03.17
[Python] 해쉬 구하기  (0) 2016.01.13
[Python] http post request  (0) 2016.01.05
Comments