진박사의 일상

[Python] id() 함수와 ctypes 본문

프로그래밍

[Python] id() 함수와 ctypes

진박사. 2021. 9. 18. 16:56
import ctypes

a = [1,'1',1.0,None]
>>> for i in a:
	b = ctypes.cast(id(i), ctypes.py_object)
	print(b, b.value, type(b), type(b.value))


'''
py_object(1) 1 <class 'ctypes.py_object'> <class 'int'>
py_object('1') 1 <class 'ctypes.py_object'> <class 'str'>
py_object(1.0) 1.0 <class 'ctypes.py_object'> <class 'float'>
py_object(None) None <class 'ctypes.py_object'> <class 'NoneType'>
'''

오늘의 발견

id 함수는 특정 개체의 주소값을 가져오고 ctype.cast는 그 id를 py_object로 변환한다. 그리고 그 cast된 결과의 value값을 가져오면 원래 class에 맞는 type으로 반환이 된다. 이를 잘 활용하면 python에서도 c의 포인터 비스무리한 것을 할 수 있을지도..