Python Glossary Русский

all Python 3ctypesfunction

ctypes.byref

pointers

Pass a ctypes object to a C function by reference — like &x in C — so the function can write a result into the variable.

Syntax

lib.func(ctypes.byref(x))

Use it when a C function returns a value through a pointer parameter, like sscanf or functions that fill a struct. It is lighter and faster than ctypes.pointer but only fit for passing into a call: you cannot store a byref result and dereference it. Only ctypes objects — c_int, Structure, arrays — can be passed by reference, not a plain Python int.

Examples

import ctypes
import ctypes.util
libc = ctypes.CDLL(ctypes.util.find_library('c'))   # → ? имя библиотеки зависит от системы
n = ctypes.c_int(0)
libc.sscanf(b'17', b'%d', ctypes.byref(n))   # → ? sscanf есть в библиотеке C на Unix
print(n.value)   # → 17
print(ctypes.pointer(n).contents.value)   # → 17 — pointer даёт настоящий указатель

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy