0Pricing
Python Academy · 강의

ctypes: Python에서 C 라이브러리 호출하기

공유 라이브러리를 불러오고 ctypes로 C 함수를 호출합니다.

ctypes: Python에서 C 라이브러리 호출하기은(는) CoddyKit의 무료 Python Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Python Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Python Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

ctypes란 무엇인가요?

ctypes는 공유 C 라이브러리를 로드하고 Python에서 해당 함수를 호출하기 위한 표준 라이브러리 모듈입니다. 컴파일할 필요가 없습니다.

import ctypes

# Load the C standard library
libc = ctypes.CDLL("libc.so.6")   # Linux
# libc = ctypes.CDLL("libSystem.dylib")  # macOS

libc.puts(b"Hello from C!")

라이브러리 로드

cdecl 호출 규약을 사용하는 대부분의 C 라이브러리에는 ctypes.CDLL을 사용하고, Windows stdcall API에는 WinDLL을 사용합니다.

import ctypes

# Platform-independent approach:
import ctypes.util
libm_name = ctypes.util.find_library("m")
libm = ctypes.CDLL(libm_name)

result = libm.sqrt
result.restype = ctypes.c_double
result.argtypes = [ctypes.c_double]
print(result(2.0))   # 1.4142...

C 데이터 형식

ctypes 클래스인 c_int, c_double, c_char_p, c_void_p 등을 사용하여 Python 형식을 C 형식에 매핑합니다.

import ctypes

x = ctypes.c_int(42)
print(x.value)   # 42

d = ctypes.c_double(3.14)
print(d.value)   # 3.14

s = ctypes.c_char_p(b"hello")
print(s.value)   # b"hello"

argtypes 및 restype 설정

형식 불일치로 인해 조용히 충돌하는 일을 방지하려면 항상 argtypes(매개변수 형식)와 restype(반환 형식)를 선언하십시오.

import ctypes, ctypes.util

libm = ctypes.CDLL(ctypes.util.find_library("m"))

libm.pow.argtypes = [ctypes.c_double, ctypes.c_double]
libm.pow.restype  = ctypes.c_double

print(libm.pow(2.0, 10.0))   # 1024.0

포인터 전달

ctypes.byref(var) 또는 ctypes.pointer(var)를 사용하여 C 변수에 대한 포인터를 전달합니다.

import ctypes

libc = ctypes.CDLL(None)   # None = current process

value = ctypes.c_int(0)
# Passing pointer to C function:
# libc.some_func(ctypes.byref(value))
print(value.value)

구조체

ctypes.Structure를 상속하고 _fields_를 나열하여 C 구조체를 정의합니다.

import ctypes

class Point(ctypes.Structure):
    _fields_ = [
        ("x", ctypes.c_double),
        ("y", ctypes.c_double),
    ]

p = Point(1.0, 2.0)
print(p.x, p.y)   # 1.0 2.0

배열

TypeClass * N을 사용하여 C 배열을 생성합니다.

import ctypes

IntArray5 = ctypes.c_int * 5
arr = IntArray5(10, 20, 30, 40, 50)
for v in arr:
    print(v, end=" ")   # 10 20 30 40 50

콜백(함수 포인터)

ctypes.CFUNCTYPE을 사용하여 콜백으로 전달할 수 있는 C 호출 가능 Python 함수를 생성합니다.

import ctypes

CompareFunc = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_int)

def my_compare(a, b):
    return a - b

c_compare = CompareFunc(my_compare)
# Pass c_compare to a C function expecting a comparator

Windows DLL 로드

Windows에서는 stdcall 규약을 사용하는 DLL(예: Windows API)에 ctypes.WinDLL을 사용합니다.

import ctypes   # Windows only

kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
kernel32.GetTickCount.restype = ctypes.c_ulong
print(kernel32.GetTickCount())

오류 처리

ctypes.get_last_error()(Windows)를 확인하거나, 특수한 값으로 반환되는 오류에는 Python 수준의 try/except를 사용합니다.

import ctypes

# Many C functions return -1 or NULL on error:
result = some_c_function()
if result == -1:
    raise OSError("C function failed")

# For errno on POSIX:
import os
if result < 0:
    raise OSError(os.strerror(ctypes.get_errno()))

실전 예제: OpenSSL을 사용한 SHA-256

Python 바인딩 라이브러리 없이 ctypes를 통해 OpenSSL의 SHA256을 직접 호출합니다.

import ctypes, ctypes.util

libcrypto = ctypes.CDLL(ctypes.util.find_library("crypto"))

SHA256 = libcrypto.SHA256
SHA256.argtypes = [ctypes.c_char_p, ctypes.c_size_t, ctypes.c_char_p]
SHA256.restype  = ctypes.c_char_p

buf = ctypes.create_string_buffer(32)
SHA256(b"hello", 5, buf)
print(buf.raw.hex())

빠른 확인

ctypes 함수에서 항상 argtypes와 restype를 설정해야 하는 이유는 무엇입니까?

복습

ctypes는 컴파일 없이 공유 C 라이브러리를 로드합니다. 모든 함수에 argtypes와 restype를 선언하십시오. C 구조체에는 Structure를, 배열에는 TypeClass * N을, 콜백에는 CFUNCTYPE를 사용합니다.

자주 묻는 질문

“ctypes: Python에서 C 라이브러리 호출하기” 강의는 무료인가요?

네 — “ctypes: Python에서 C 라이브러리 호출하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Python Academy 강의 전체를 잠금 해제할 수 있습니다. Python Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“ctypes: Python에서 C 라이브러리 호출하기”에서 뭘 배우나요?

공유 라이브러리를 불러오고 ctypes로 C 함수를 호출합니다. 브라우저에서 직접 실행하는 실습 코드로 Python Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Python Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Python Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“ctypes: Python에서 C 라이브러리 호출하기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Python Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Python Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. C 확장이 필요한 이유: 사용 사례와 절충점
  2. ctypes: Python에서 C 라이브러리 호출하기
  3. cffi: C 외부 함수 인터페이스
  4. Python C 확장 모듈 작성
← Python Academy(으)로 돌아가기