Python Glossary Русский

all Python 3ctypesfunction

ctypes.CDLL

loading libraries

Load a C shared library (.so, .dylib, .dll) and call its functions as attributes of the returned object.

Syntax

lib = ctypes.CDLL(name)
lib.func.argtypes = [ctypes.c_int]
lib.func.restype = ctypes.c_int

Without type declarations ctypes assumes a function takes and returns int: for a double or a pointer the result is garbage. So set argtypes and restype on every function. A type mistake raises no exception and may crash the whole interpreter. Library names are platform-specific; ctypes.util.find_library('c') finds them portably.

Examples

import ctypes
import ctypes.util
libc = ctypes.CDLL(ctypes.util.find_library('c'))   # → ? имя библиотеки зависит от системы
libc.strlen.argtypes = [ctypes.c_char_p]
libc.strlen.restype = ctypes.c_size_t
print(libc.strlen(b'hello'))   # → ? 5 — функция стандартной библиотеки C

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy