Rotiple



python에서 DLL을 로딩하려면 ctypes를 이용하여야 한다.
ctypes는 다양한 호출 규약(Calling Convention)을 지원한다. 즉, 다양한 c
ctypes는 cdll, windll, oldell 호출 규약을 지원한다.
cdll은 cdecl 호출 규약을 지원하고, windll은 stdcall 호출 규약을 지원하며, oldell은 windll과 동일한 호출 규약을 지원하지만 반환 값을 HRESULT로 가정한다는 차이점이 있다.

Win32 API 호출

import ctypes
ctypes.windll.user32.SetWindowsHookExA



API 호출할 때 전달하는 인자의 자료형을 지정할 수 있다.

from ctypes import *
msvcrt = cdll.msvcrt
printf = msvcrt.printf
printf.argtypes = [c_char_p, c_char_p, c_int, c_double]
printf("String '%s', Int %d, Double %f\n", "Hi", 10, 2.2)



자료형
파이썬은 ctypes 모듈에서 제공하는 자로형을 이용해서 C언어의 자료형을 사용할 수 있다. C언어의 정수형ㅇ르 사용하려면 다음과 같이 ctypes을 활용한다.

from ctypes import *
i = c_int(42)


주소를 저장하는 포인터형을 선언해서 사용할 수 있다.

from ctypes import *
P1 = POINTER(c_int)



변수형 매핑 테이블



포인터의 전달
함수의 인자로 포인터(값의 주소)를 전달할 수 있다.

from ctypes import *
f = c_float()
s = create_string_buffer('\00' * 32)
windll.msvcrt.sscanf("1 3.14 Hello", "%f %s", byref(f), s)

콜백 함수
특정 이벤트가 발생하는 함수인 콜백 함수를 선언해서 전달할 수 있다.

구조체
Structure 클래스르 상속 받아 구조체 클래스를 선언할 수 있다.

from ctypes import * class POINT(structure): #선언     _fields_ = [("x", c_int), ("y", c_int)] point = POINT(10,20) #사용