2012-06-02 ctypes 라이브러리 : 동적 링크 라이브러리(Dynamic Linked Library) 함수의 호출을 가능하게 하고, C데이터 타입을 사용할 수 있으며, 메모리를 관리하는 로우레벨 함수를 제공함 cdll() : 표준 cdecl 호출 규약을 이용하는 함수를 export하는 라이브러리를 로드 windll() : win32 API가 사용하는 stdcall 호출 규약을 사용해 함수를 export하는 라이브러리를 로드 oledll() : 위와 동일하게 동작하지만 export함수가 반환하는 값이 HRESULT라 가정 HRESULT : http://blog.naver.com/kkan22?Redirect=Log&logNo=80051298175 MS Component Object Model 에서 에러메시지를 반환하기위해 특별하 사용되는 것
함수 호출 규약의 이해 호출 규약(calling convention)은 함수를 어떻게 호출하는지 그 방법을 정의한 것으로 함수에 파라미터를 전달하는 순서와 전달된 파라미터가 스택에 어떻게 PUSH되는지, 함수가 리턴되면서 스택이 어떻게 정리되는지 여부를 정의한것. *cdecl 함수 호출의 경우 C : int python_rocks(reason_one, reason_two, reason_three); x86 asm : push reason_three push reason_two push reason_one call python_rocks add esp, 12 *stdcall 함수 호출의 경우 C : int my_socks(color_one, color_two, color_three); x86 asm: push color_three push color_two push color_one call my_socks 위와 다르게 함수 호출자가 스택을 정리하는대신 my_socks 함수가 리턴하기 직전 정리 두 호출 규약 모두 eax를 이용해 리턴값을 전달한다.
c type python type ctypes type char 한 문자 c_char wchar_t 유니코드 한 문자 c_wchar char int/long c_byte char int/long c_ubyte short int/long c_short unsigned short int/long c_ushort int int/long c_int unsigned int int/long c_uint long int/long c_long unsigned long int/long c_ulong long long int/long c_longlong unsigned long long int/long c_ulonglong float float c_float double float c_double char * (NULL terminated) string or none c_char_p wchar_t * (NULL terminated) unicode or none c_wchar_p void * int/long 또는 none c_void_p
+example >>> from ctypes import * >>> seitz = c_char_p("loves the python") >>> print seitz c_char_p('loves the python') >>> print seitz.value loves the python 포인터의 내용에 접근하려면 .value를 이용하야 한다. 이를 포인터에 대한 dereferencing(역참조)라 한다.
ctypes에서 포인터를 함수의 파라미터로 전달하기 function_main( byref(parameter) )
구조체 C : struct beer_recipe { int amt_barley; int amt_water; } Python : class beer_recipe(Structure): _fields_=[ ("amt_barley", c_int), ("amt_water", c_int), ]
유니언 C : union { long barley_long; int barley_int; char barley_char[8]; }barley_amount; Python : class barley_amount(Union): _fields_=[ ("barley_long", c_long), ("barley_int", c_int), ("barley_char", c_char * 8), ]
class barley_amount(Union): _fields_ = [ ("barley_long", c_long), ("barley_int", c_int), ("barley_char", c_char * 8), ] value = raw_input("Enter the amount of barley to put into the beer vat:") my_barley = barley_amount(int(value)) print "Barley amount as a long: %ld" % my_barley.barley_long print "Barley amount as a int: %d" % my_barley.barley_int print "Barley amount as a char: %s" % my_barley.barley_char