Python에서 ctypes.addressof()
함수의 반환값(메모리 주소)을 이용해 일정 길이만큼 bytes 객체를 만드는 방법을 알아 보겠습니다.
방법 1: ctypes.string_at() 사용 (권장)
import ctypes
# 예시: 배열 생성
arr = (ctypes.c_int * 5)(1, 2, 3, 4, 5)
addr = ctypes.addressof(arr)
# 주소에서 특정 길이만큼 bytes로 읽기
length = ctypes.sizeof(arr) # 또는 원하는 길이
data = ctypes.string_at(addr, length)
print(type(data)) # <class 'bytes'>
print(data.hex()) # 0100000002000000030000000400000005000000
방법 2: ctypes.cast()와 POINTER 사용
import ctypes
arr = (ctypes.c_int * 5)(1, 2, 3, 4, 5)
addr = ctypes.addressof(arr)
length = 20 # 읽고 싶은 바이트 수
# 주소를 char 포인터로 캐스팅
char_ptr = ctypes.cast(addr, ctypes.POINTER(ctypes.c_char * length))
data = bytes(char_ptr.contents)
print(data.hex()) # 0100000002000000030000000400000005000000
방법 3: from_address() 사용
import ctypes
arr = (ctypes.c_int * 5)(1, 2, 3, 4, 5)
addr = ctypes.addressof(arr)
length = 20
# 주소에서 배열 생성 후 bytes로 변환
char_array = (ctypes.c_char * length).from_address(addr)
data = bytes(char_array)
print(data.hex()) # 0100000002000000030000000400000005000000
실제 사용 예시
import ctypes
# 구조체 예시
class Point(ctypes.Structure):
_fields_ = [("x", ctypes.c_int), ("y", ctypes.c_int)]
point = Point(10, 20)
addr = ctypes.addressof(point)
# 구조체 크기만큼 bytes로 읽기
size = ctypes.sizeof(Point)
data = ctypes.string_at(addr, size)
print(f"Point as bytes: {data}")
print(f"Length: {len(data)}")
맺는말
ctypes.addressof() 함수를 이용용하여 메모리 주소를 직접 다루므로 잘못된 길이나 주소 사용 시 프로그램이 충돌할 수 있습니다. 메모리 주소에서 읽으려는 길이가 실제 할당된 메모리 크기를 초과하지 않도록 주의해야 합니다.
위 세가지 방법 중에서 ctypes.string_at()
이 가장 안전하고 직관적인 방법입니다.
728x90
반응형
'프로그래밍 > Python' 카테고리의 다른 글
[python] weekday를 각 OS 언어별 문자열로 변환하는 방법 (0) | 2025.06.20 |
---|---|
[python] requests - 응답을 UTF-8로 지정하여 받는 방법 (0) | 2025.06.13 |
[python] pytest에서 "ModuleNotFoundError: No module named 'apt_pkg'" 오류 발생 문제 (0) | 2025.06.07 |
[python] 쉘의 파이프 "|"를 subprocess.Popne()으로 처리하는 방법 (0) | 2025.04.14 |
PyInstaller - "ModuleNotFoundError: No module named 'debugpy'" 문제 해결하기 (0) | 2025.04.09 |