numbox.core.bindings
Overview
A binding lets jitted code call a C function. It is a numbox function with the C function’s name and arguments, and a
jitted call of it runs the C function. numbox has bindings for the C standard library, the C math library and SQLite.
They include functions that numba’s own support
lacks: files through fopen and fwrite, raw memory through memcpy, formatted output to C streams and buffers
through printf and snprintf, math functions such as remainder, and the SQLite API. A jitted function that
calls bindings can be cached with cache=True, and it keeps working when a later process loads it from the cache. Its
compiled code refers to each binding and each C function by name, never by address, and numbox loads the libraries in
that process as well, so that LLVM finds the names again.
numbox loads the dynamic libraries that it binds, such as libc, libm and libsqlite3, through ctypes. On
Linux and macOS, ctypes.util.find_library finds each library by its short name in the system’s library search, not
in the Python installation. On Windows, numbox loads the C runtime msvcrt.dll for libc and libm, and the
sqlite3.dll that comes with Python. On Linux and macOS, numbox opens the libraries in global symbol mode
(RTLD_GLOBAL, see dlopen(3)). Global mode makes the symbols
that the libraries export, their native C API, visible to LLVM, which finds a symbol by name when it links compiled code
into the process. Jitted code can then call these C functions [1], which complement the functions that numba supports
itself.
The same technique serves for a C library of your own. Load the library with
load_lib() or load_lib_path(), declare each function
with numba’s ExternalFunction, and call it from a function decorated with proxy().
The proxy decorator compiles the function once, when its module is imported, and every jitted caller then calls that
one compiled copy by name. Use proxy_if_available() instead for a symbol that some
versions of the library lack. The proxy page shows such a binding in its section on optional C symbols.
References
Calling a binding
Import a binding from its module and call it in jitted code:
from numba import njit
from numbox.core.bindings.libc import strlen
from numbox.core.bindings.libm import remainder
from numbox.utils.lowlevel import get_unicode_data_p
@njit(cache=True)
def demo(word):
return remainder(7.0, 2.0), strlen(get_unicode_data_p(word))
print(demo("numbox")) # (-1.0, 6)
C’s remainder rounds the quotient 3.5 to the nearest even integer, 4, and returns 7.0 - 4 * 2.0, which is
-1.0. strlen takes a pointer, passed as an intp integer, and
get_unicode_data_p() returns the address of a string’s characters. C reads those characters
as text only for an ASCII string, as the section Pointers and memory explains. Python code can call the same
bindings, and remainder(7.0, 2.0) returns -1.0 there too.
Bindings module conventions
numbox defines its bindings in these modules:
numbox.core.bindings.libc: string, memory, file and environment functions of the C standard library, such asstrlen,memcpy,fopenandgetenv;numbox.core.bindings.libm: the functions of the C math library, onfloat64;numbox.core.bindings.stdio: the standard streams;numbox.core.bindings.errno: reading and settingerrno;numbox.core.bindings.strerror: a thread-safe message for an error number;numbox.core.bindings.fmtio:printf,fprintf,snprintfandsscanf;the subpackage
numbox.core.bindings.sqlite: the SQLite API, described on its own page.
The remaining modules are internal, so you seldom call them directly:
numbox.core.bindings.call:_call_lib_func, the internal helper through which the libc, libm and SQLite bindings call C, described in its source;numbox.core.bindings.abi: the rules by which the helper passes values on each platform;numbox.core.bindings.signatures: the table of C signatures;numbox.core.bindings.utils:load_lib(),load_lib_path()and helpers for the binding modules.
The helper knows the calling conventions of x86-64 on Linux, macOS and Windows, and of 64-bit Arm on Linux and macOS. On
another machine, the first import of libc, libm or a SQLite module fails with a RuntimeError that names the
platform, because the import compiles the bindings through the helper.
A binding in libc, libm, fmtio or the SQLite subpackage has its C function’s name and takes the C function’s arguments
in their C order. The C function’s manual page is therefore its reference: the Linux man pages, Apple’s Libc sources
for macOS, and Microsoft’s C runtime reference for Windows. libm’s round
and pow are C’s functions, not Python’s: C’s round(2.5) is 3.0, and Python’s is 2. Import the module, as
in from numbox.core.bindings import libm, and call libm.round, so that the name round keeps its Python
meaning.
Every binding outside fmtio is a proxied function, made with the proxy decorator that the Overview describes. numbox
compiles it once, when its module is imported, and a jitted caller calls it by name instead of compiling a copy of its
code into each caller. A caller’s own compiled code therefore stays small, and a cached caller works in a later process.
The drawback is that each call remains a function call, because LLVM cannot inline it. Python code can call a proxied
binding as well.
A binding’s .as_func is a first-class function value for the binding’s signature, and a jitted function can take it
as an argument, as the proxy page’s section on passing the function as a value shows.
Pass .as_func, not the binding itself. The binding is a numba dispatcher, the object that @njit returns, and its
numba type names the address of the function it wraps, so a cached function that receives it compiles again on every
run.
numba caches the bindings under numbox’s jit options, the numba options that the NUMBOX_JIT_OPTIONS environment
variable sets (numbox.core.configurations). A later import loads the bindings from the cache unless those options
disable caching. numbox also disables caching, with a warning, where numba can write no cache. The package
numbox.core.bindings imports none of its modules, so a module you do not import is never compiled.
Cached callers of a binding keep working after a numbox upgrade from one release to another. The bindings compile again,
because their cache key holds numbox’s version, as after you upgrade numbox explains.
numbox repairs each cached caller of a binding whose code the new release changed, at the caller’s next run and with one
warning, as the proxy page says under After you upgrade numbox. The one case that repair
does not cover is a caller that holds a binding’s .as_func in a module-level variable. Delete that caller’s cache
files, as holding the function as a module-level constant explains.
A few SQLite bindings name symbols that some builds of SQLite lack, such as sqlite3_changes64, which SQLite added in
version 3.37. Where the symbol is missing, the binding is a stub, and a jitted caller fails to compile, as the
proxy page’s section on optional C symbols explains. fmtio’s functions are not proxied:
numba compiles each call of them into its caller, and the section Caching callers of the formatted I/O functions says
how that changes a cached caller’s behavior after an upgrade.
The bindings in libc, libm and the SQLite subpackage take their signatures from one table, the dictionary signatures
in numbox/core/bindings/signatures.py, keyed by C name. strchr, for
example, is intp(intp, int32): it takes a pointer and an int32 and returns a pointer. The table writes C’s
int as int32, long long as int64, double as float64, and size_t and every pointer as
intp. It holds no C long, which has 64 bits on Linux and macOS and 32 bits on Windows; when you declare a C
function that takes a long, use int64 on Linux and macOS and int32 on Windows. A jitted caller may pass
another numeric type, and numba converts it to the table’s type without a warning. For example, C receives 65 when
the caller passes 65.7 or 2**40 + 65 for an int32. The stdio, errno and strerror modules declare their
signatures in their own code.
Pointers and memory
A pointer is an intp integer, and numbox does not check it. The caller keeps the memory alive while C uses it, and
makes it large enough, and aligned, for what C reads or writes. numbox.utils.lowlevel converts between Python
objects and pointers:
array_data_p()returns the address of a NumPy array’s data;get_unicode_data_p()returns the address of a string’s characters;get_str_from_p_as_int()copies a NUL-terminated C string into astr, one character per byte.
In jitted code, numba frees an array or a string as soon as the code no longer refers to it, and an address taken from
the object does not count as a reference. A temporary, such as the result of a + b in
strlen(get_unicode_data_p(a + b)), is therefore freed before strlen reads it. numba frees a named array in the
same way when array_data_p(x) is the last place that names x. C then reads freed memory: a small object may
still hold its old bytes, and a large one ends the process with a segmentation fault. Name the object and refer to it
after the C call, for example by reading its length, or pass it in from the caller, as the examples on this page do. A
string literal or a module-level string is safe: numba holds it as a constant and never frees it, so
get_unicode_data_p("r") inside a call works.
Called from Python, get_unicode_data_p returns an address inside the str object itself, so keep the string alive
while C uses it.
C reads a string’s characters as text only if the string is ASCII. numba and CPython store each string at one, two or
four bytes per character, a width set by its widest character, and never as UTF-8. For other text, encode the string as
UTF-8 in Python, add a NUL, and pass the address of the bytes as a uint8 array:
import numpy as np
from numba import njit
from numbox.core.bindings.libc import strlen
from numbox.utils.lowlevel import array_data_p
@njit(cache=True)
def byte_count(text):
return strlen(array_data_p(text))
text = np.frombuffer("caf\u00e9".encode("utf-8") + b"\0", dtype=np.uint8)
print(byte_count(text)) # 5: four characters, five UTF-8 bytes
c_string() builds the same bytes from Python and keeps them alive for the length of a
with block.
Passing a struct
numbox’s bindings pass only numbers and pointers. Store a struct in a one-element NumPy structured array, and pass
array_data_p of the array to a C function that takes a pointer to the struct. Build the dtype with align=True,
so that NumPy places the fields where a C compiler does: np.dtype([("x", np.int32), ("y", np.float64)], align=True)
puts y at offset 8, as C does, and without align=True NumPy puts it at offset 4.
A C function that takes a struct by value is harder to call. numba’s ExternalFunction cannot pass a struct by value
at all: a jitted call of a function declared with a tuple argument fails to compile with an AssertionError. Passing
one through numbox’s internal helper and its table of signatures is a method specific to numbox. That method is fragile:
a struct written as a numba tuple reaches C intact, on x86-64 Linux only, in these four cases:
it has a single field;
it is larger than 16 bytes;
it is exactly 16 bytes, with one field in each 8-byte half;
it is exactly 16 bytes, with two or more fields in a half, and neither half is made only of floating-point fields.
(int32, int32, int64) matches the last case and reaches C intact. (int32, int32, float64) matches no case,
because its upper half holds only a float64. C reads a wrong value for its second int32. A struct smaller than
16 bytes with two or more fields, such as the 8-byte div_t that C’s div returns, is corrupted as well.
A numba record cannot be passed by value in either direction. Passed as an argument, it reaches C as the address of its data instead of its fields, and a record result of 16 bytes or less ends the process with a segmentation fault.
The helper also refuses some calls when numba compiles them, with a TypingError whose message contains the text
below:
is unavailable in the LLVM context: no loaded library exports the symbol; load its library withload_libfirst;Undefined signature for: the table has no entry for the name;Record returns >16 bytes are not yet supported: return a tuple of the same fields instead;has no fixed bitwidth: a tuple field, such as avoidptr, has no fixed size; pass the pointer as anintp.
Loading a library
You need load_lib() only to bind a library of your own, because each numbox binding
module calls it for its own library when imported. load_lib takes a short name, such as "c", "m" or
"sqlite3", and returns the library’s handle, an ordinary ctypes.CDLL. The handle remains loaded for the lifetime
of the process. A second call with the same name returns the same handle. On Linux and macOS, load_lib finds the
file with ctypes.util.find_library. That function uses the system’s library search and does not look in the Python
installation, as the ctypes documentation
describes. It then opens the file in global symbol mode. A plain ctypes.CDLL opens a library in local mode instead,
where its symbols are not visible to LLVM. A jitted call of one of its functions through ExternalFunction then ends
the process with a segmentation fault.
When find_library finds no file, load_lib raises RuntimeError: Could not find shared library for <name>.
Pass the file’s path to load_lib_path() instead, which opens the file in the same mode
and returns a new handle on each call. On Windows, "c" and "m" load the C runtime msvcrt.dll. For any other
name, load_lib prefers the DLL bundled with the Python installation to one found on the PATH, and for
"sqlite3" it takes only the bundled one.
On Linux, every libm binding runs the system’s libm. On Windows, 26 of them, such as cos, pow, sqrt and
fmod, run CPython’s C runtime instead of the msvcrt.dll that numbox loads for "m". numba registers those 26
names for its own math support, and LLVM looks up numba’s registration before any library.
When numba’s JIT is disabled
Under NUMBA_DISABLE_JIT=1, numba compiles nothing, and importing any module of proxied bindings fails with
AttributeError: 'function' object has no attribute 'get_compile_result'. The message means that proxy needs
numba’s compiler, which the setting disables; unset the variable to use these bindings. fmtio still imports, and
printf runs under Python. fprintf fails with the same AttributeError, because it imports the stdio bindings.
snprintf writes through a ctypes call that accepts only a Python int as the address. With numba’s JIT
disabled, array_data_p returns a NumPy integer, so pass int(array_data_p(buf)).
Writing to stdout and stderr
C functions that work on a stream, such as fputs, fflush and fprintf, take the stream’s FILE *.
stdout(), stderr() and
stdin() return the current process’s three standard streams as intp values, in
jitted code and under Python. They are functions, not constants, because a cached caller’s compiled code must not
contain an address from the process that compiled it. A stream’s address changes from one process to the next, so each
call reads the address in the running process. Here jitted code writes one line to each stream:
from numba import njit
from numbox.core.bindings.libc import fflush, fputs
from numbox.core.bindings.stdio import stderr, stdout
from numbox.utils.lowlevel import get_unicode_data_p
@njit(cache=True)
def report(line, warning):
fputs(get_unicode_data_p(line), stdout())
fflush(stdout())
fputs(get_unicode_data_p(warning), stderr())
report("42 rows written\n", "2 rows skipped\n")
C keeps a buffer for its stdout, and Python keeps another for sys.stdout. When stdout is a file or a pipe, each
writes its buffer only when the buffer fills, when the program flushes it, or when the process exits. Lines from jitted
code and lines from Python can then appear out of order. If the process crashes, C never writes the text that remains in
its buffer. To keep the order, flush Python’s buffer with sys.stdout.flush() before the jitted call. In jitted code,
call fflush(stdout()) after the write, as report does; fflush(0) flushes every C stream. On Linux, C writes
stderr without a buffer (setbuf(3)), so a warning appears
immediately. On Windows, C flushes a stderr that goes to a file or a pipe only when its buffer fills (Microsoft’s
stream I/O), so call
fflush(stderr()) there as well.
Reading errno after a failed call
A C function that fails, such as fopen on a missing file, returns a failure value and leaves the reason in errno
(errno(3)). errno_get()
returns the current thread’s errno as an int32. errno_set() sets it, and
narrows its argument to int32. Read errno in the jitted function that made the call, immediately after the call,
because a later C call may change it:
from numba import njit
from numbox.core.bindings.errno import errno_get
from numbox.core.bindings.libc import fclose, fopen
from numbox.utils.lowlevel import get_unicode_data_p
@njit(cache=True)
def open_error(path):
fp = fopen(get_unicode_data_p(path), get_unicode_data_p("r"))
if fp == 0:
return errno_get()
fclose(fp)
return 0
print(open_error("/no/such/file")) # 2, which is errno.ENOENT
Each thread has its own errno, and both functions look up the current thread’s on every call. In a prange loop
(parallel loops), an iteration
therefore reads the errno of the thread that runs it. Read errno in the iteration that made the C call, because
the caller’s errno after the loop depends on the threading layer. Under OpenMP, which numba selects when TBB is not
installed (threading layers),
the calling thread runs some iterations itself. After the loop, its errno holds the value set by those iterations.
Under the workqueue layer, the calling thread runs no iterations, and its errno is unchanged.
Turning an error number into a message
strerror_safe() writes the message for an error number into a buffer that the
caller provides, and ends the message with a NUL. It returns 0 on success and an error number on failure. libc’s
strerror may return a buffer that a later call overwrites; strerror_safe keeps no buffer of its own, so threads
can call it at the same time:
import numpy as np
from numba import njit
from numbox.core.bindings.strerror import strerror_safe
from numbox.utils.lowlevel import array_data_p, get_str_from_p_as_int
@njit(cache=True)
def describe(errnum, buf):
rc = strerror_safe(errnum, array_data_p(buf), buf.size)
return rc, get_str_from_p_as_int(array_data_p(buf))
print(describe(2, np.zeros(128, dtype=np.uint8))) # (0, 'No such file or directory')
With glibc, strerror_safe returns EINVAL (22) for an unknown error number and writes Unknown error followed
by the number. It returns ERANGE (34) for a buffer too short for the message and writes as much of the message as
fits. On Linux, strerror_safe calls __xpg_strerror_r, the POSIX form of strerror_r that glibc exports, and falls back to strerror_r where
the C library lacks it; on macOS it calls strerror_r, and on Windows strerror_s.
Formatted output and input
printf(), fprintf(),
snprintf() and sscanf() take a format string and the
values after it, as C’s functions do (printf(3), sscanf(3)). They are ordinary Python functions that numba also compiles,
as it compiles print, so one function body can run under Python and in jitted code:
from numba import njit
from numbox.core.bindings.fmtio import printf
from numbox.core.bindings.libc import fflush
from numbox.core.bindings.stdio import stdout
def step(n, label):
printf("step %d: %s\n", n, label)
fflush(stdout())
return 2 * n
step(7, "in Python")
njit(step)(7, "in jitted code")
Under Python, printf formats the values with Python’s % operator and writes the text to the current
sys.stdout, so a redirection such as contextlib.redirect_stdout reaches it. fprintf maps the addresses that
stdout(), stderr() and stdin() return to the sys.stdout, sys.stderr and sys.stdin objects that
it finds at its first call. A redirection installed after that first call does not change where fprintf writes.
fprintf raises RuntimeError for any other FILE *, such as one from fopen. snprintf writes the text
into memory at the address it receives, such as array_data_p(buf). In jitted code, numba compiles each call into a
call of C’s function, which writes to C’s streams and accepts any FILE *. sscanf runs only in jitted code, as
the section Parsing with sscanf describes.
The format string and its arguments
In jitted code, the format must be a string that numba reads as a constant: a string literal, a module-level string or a
closure variable. A format built at run time fails to compile with
TypingError: printf: format string must be a literal str; pass the part that varies as an argument instead, such as
a %s. numbox encodes the format as UTF-8, so non-ASCII text in the format prints as written. Each conversion takes
one kind of argument:
Conversions |
Argument |
|---|---|
|
an integer or a |
|
a float |
|
a |
|
a pointer |
When numba compiles the call, numbox checks the format against the arguments, as GCC’s -Wformat does. The compile fails with a TypingError
that names the problem when:
the format has more or fewer conversions than there are arguments; a
*width or precision counts as one more integer argument;a conversion gets an argument of another kind than the one it takes, apart from the two cases described below;
an argument has a type that no conversion takes, such as an array, a complex number or a tuple; pass the element or the field you mean, such as
a[0]orz.real;the format holds
%n, which would make C write the number of characters printed so far through a pointer;the format holds the
'flag for digit grouping, which POSIX defines and C99 and Python’s%lack.
numba lists each of these errors next to a second message, format string must be a literal str, got unicode_type;
read the message that names the mismatch. A literal percent sign followed by n, %%n, is allowed. Under Python,
%n and the ' flag raise ValueError.
The check cannot distinguish a pointer from an integer, because numba represents a pointer as an intp, which is an
int64. It also sees a str as the address of its characters, because numbox substitutes that address before the
check runs. A %s given an int64 value compiles, and C then reads memory at that address, which usually ends
the process with a segmentation fault. A %d given a str compiles as well, and C prints the address. Pass
%s a str or the address of a NUL-terminated buffer, and pass an integer conversion an integer. %p only
prints its argument as an address, so an int64 argument for %p is harmless.
For %s, numbox passes a str as the address of its characters, so the ASCII limit from the section
Pointers and memory applies: "caf\xe9" prints its last character as the single byte 0xE9, not as UTF-8. Pass
other text as a uint8 array of UTF-8 bytes, built as that section shows. A width, as in %-10s, counts bytes, not
characters.
When Python and C print differently
If the format uses an ll conversion for every integer, %lld for a signed value and %llu for an unsigned one,
the call prints the same under Python and in jitted code. Other conversions can print differently. Python’s %
operator ignores a single h, l or L and rejects any other length modifier, as its documentation says: "%lld" % 5 raises
ValueError: unsupported format character 'l'. Under Python, numbox therefore removes every length modifier from the
format before it formats, and with the modifiers gone, Python prints each value at its full size. In jitted code, numbox
passes every integer and bool as 64 bits and every float as a float64, and C converts each value to the type
that its conversion names, such as int for %d or signed char for %hhd. A value that fits that type
prints the same under Python and in jitted code, and a value that does not fit prints differently:
Format |
Value |
Python |
jitted code |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The Python path has one known inconsistency: its stripping does not skip the %% escape, so it also removes a
modifier that follows a literal %%, and printf("%%lld\n") prints %d under Python and %lld in jitted
code. On Windows, C’s long has 32 bits (Microsoft’s data type ranges), so %ld reads only 32 bits of an int64 there.
Python accepts some calls that jitted code refuses, such as %f with an integer and %d with a float. %p works
only in jitted code, because Python’s % rejects it.
Checking snprintf for truncation
snprintf(buf, size, fmt, ...) writes at most size bytes into buf, the terminating NUL included, and returns
the length of the whole text. A return value of size or more therefore means that snprintf truncated the text.
In jitted code, buf and size must be intp values. a.size, np.intp(16) and an int64 argument of
the jitted function, such as a Python int passed in, are intp, but a literal is not: snprintf(p, 16, ...)
fails to compile with TypingError: snprintf: size must be intp (size_t-as-int), got Literal[int](16). The message
means that numba typed the literal 16 as a literal integer; pass a.size or np.intp(16) instead.
On Windows, jitted code calls C’s _snprintf
instead. It returns -1 when the text is longer than size, and when the text is exactly size bytes long it
returns size and writes no terminating NUL. The test n < 0 or n >= size covers both cases on every platform:
import numpy as np
from numba import njit
from numbox.core.bindings.fmtio import snprintf
from numbox.utils.lowlevel import array_data_p
@njit(cache=True)
def format_range(buf, lo, hi):
n = snprintf(array_data_p(buf), buf.size, "[%d:%d]", lo, hi)
return -1 if n < 0 or n >= buf.size else n
buf = np.zeros(16, dtype=np.uint8)
n = format_range(buf, 7, 11)
print(n, bytes(buf[:n]).decode()) # 6 [7:11]
Under Python, snprintf follows the C99 rule on every platform.
Parsing with sscanf
sscanf(buf, fmt, ...) reads values from the NUL-terminated text at buf into storage that the caller provides. It
returns the number of values that it stored, or -1 (EOF) when the text ends before the first conversion. Unlike
the other three functions, it runs only in jitted code. Under Python it raises NotImplementedError, and int(),
float() or re parse the text there instead. A jitted function calls sscanf as follows:
import numpy as np
from numba import njit
from numbox.core.bindings.fmtio import sscanf
from numbox.utils.lowlevel import array_data_p, get_unicode_data_p
@njit(cache=True)
def parse_pair(text):
count = np.zeros(1, dtype=np.int32)
ratio = np.zeros(1, dtype=np.float64)
n = sscanf(get_unicode_data_p(text), "%d %lf", array_data_p(count), array_data_p(ratio))
return n, count[0], ratio[0]
print(parse_pair("42 0.25")) # (2, 42, 0.25)
buf must be an intp, so pass get_unicode_data_p(text), not the string; the ASCII limit from the section
Pointers and memory applies to the text. Each argument after the format is the address of the storage for one
conversion, also as an intp. numbox checks only that type, so an int64 value that is not an address compiles. C
then treats the value as an address and writes to the memory that it points to. numbox does not compare the format with
the arguments either, so the caller must make them match the format in number and in size. Each conversion writes
storage of its own size:
Conversion |
Storage |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
a |
|
|
Give %s a width one less than the array’s size, such as %15s for 16 bytes, so that the characters and the NUL
fit. Unlike the output functions, sscanf accepts %n: it stores the number of characters read so far, and the
return value does not count it.
Caching callers of the formatted I/O functions
A jitted call of printf, fprintf, snprintf or sscanf compiles into its caller: the caller’s code names
C’s function and holds the format as a constant. A caller cached with cache=True works in a later process, which
finds C’s function by name. After you upgrade numbox, however, a cached caller still runs the fmtio code of the numbox
version that compiled it. This happens because numba’s cache key covers the caller’s own file and not the code of the
functions it calls (what the key leaves out). Delete the caller’s cache files after an
upgrade; where numba writes the cache says where they are. Alternatively, decorate the
caller with numbox_njit(), whose cache key holds numbox’s version, so that an upgrade from
one release to another recompiles it. The cache_key page lists which functions numbox keys. It also explains what an upgrade changes, both between
releases and in a source checkout, where the version stays empty.
Modules
numbox.core.bindings.libc
Bindings for C standard library functions on strings, memory, streams, random numbers and the environment.
Each binding has the C function’s name and takes its arguments in C’s order, with the types of the function’s entry in
numbox.core.bindings.signatures: C’s int as int32, and size_t and every pointer as intp. A
pointer is an address that the caller keeps alive while C uses it, and numba converts another numeric argument to the
entry’s type without a warning. Each binding is a proxied function that jitted code and Python can call, and its
docstring links the C function’s Linux manual page. The section “Bindings module conventions” on the bindings page
describes the conventions that all binding modules share.
- numbox.core.bindings.libc.clearerr(fp)[source]
Clear the end-of-file and error indicators of the stream
fp.C reference: clearerr(3).
- numbox.core.bindings.libc.fclose(fp)[source]
Flush the buffered output of the stream
fp, close the stream, and return 0, orEOFon error.C reference: fclose(3).
fpis invalid after the call, whatever the result, and must not be used again.
- numbox.core.bindings.libc.feof(fp)[source]
Return a nonzero value if the end-of-file indicator of the stream
fpis set, and 0 if it is not.C reference: feof(3).
clearerrclears the indicator, as do C’sfseek,fsetposandrewindwhen they succeed; numbox binds none of those three.
- numbox.core.bindings.libc.ferror(fp)[source]
Return a nonzero value if the error indicator of the stream
fpis set, and 0 if it is not.C reference: ferror(3).
clearerrclears the indicator, as does C’srewind, which numbox does not bind.
- numbox.core.bindings.libc.fflush(fp)[source]
Flush the buffered output of the stream
fp, or of every output stream iffpis 0.C reference: fflush(3).
The result is 0 on success and
EOFon error. Because C buffers its stdout apart from Python’ssys.stdout, text from jitted code and text from Python can appear out of order when stdout is a file or a pipe, until both are flushed.
- numbox.core.bindings.libc.fopen(path, mode)[source]
Open the file whose name is the string at
path, in the mode given by the string atmode, as a stream.C reference: fopen(3).
pathandmode, such as"r","wb"or"a+", areintpaddresses of NUL-terminated strings. The result is aFILE *as anintp, or 0 on error, with the reason inerrno. The caller closes the stream withfclose. On Windows, a mode withoutbopens the file in text mode, which translates line endings.
- numbox.core.bindings.libc.fputc(c, fp)[source]
Write
c, converted tounsigned char, to the streamfp, and return the byte written.C reference: fputc(3).
The result is
EOFon error.fpis aFILE *as anintp.
- numbox.core.bindings.libc.fputs(s, fp)[source]
Write the NUL-terminated string at address
sto the streamfp, without a newline.C reference: fputs(3).
The result is non-negative on success and
EOFon error.sis anintpaddress that the caller keeps alive during the call, andfpis aFILE *as anintp, fromfopenor fromnumbox.core.bindings.stdio.
- numbox.core.bindings.libc.fread(ptr, size, nmemb, fp)[source]
Read up to
nmembelements ofsizebytes each from the streamfpinto memory at addressptr.C reference: fread(3).
The result is the number of elements read, which is less than
nmembat the end of the file or on an error;feofandferrordistinguish the two cases.ptris theintpaddress of at leastsize * nmembbytes, which the caller keeps alive during the call.
- numbox.core.bindings.libc.fwrite(ptr, size, nmemb, fp)[source]
Write
nmembelements ofsizebytes each from addressptrto the streamfp.C reference: fwrite(3).
The result is the number of elements written, which is less than
nmembonly on error.ptris anintpaddress that the caller keeps alive during the call, andfpis aFILE *as anintp.
- numbox.core.bindings.libc.getenv(name)[source]
Return the address of the value of the environment variable named by the string at
name, or 0 if unset.C reference: getenv(3).
The environment owns the value: the caller must not modify or free it, and a later
setenv,putenvorunsetenvcan invalidate it. To keep the value, copy it into astrwithget_str_from_p_as_int()before the environment changes.
- numbox.core.bindings.libc.memchr(s, c, n)[source]
Return the address of the first byte equal to
cin thenbytes at addresss, or 0 if none.C reference: memchr(3).
C converts
ctounsigned char, so it comparesc & 0xff.
- numbox.core.bindings.libc.memcmp(a, b, n)[source]
Compare the first
nbytes at addressesaandb, as unsigned bytes.C reference: memcmp(3).
The result follows the sign convention of
strcmp, and the comparison does not stop at a NUL.
- numbox.core.bindings.libc.memcpy(dst, src, n)[source]
Copy
nbytes from addresssrcto addressdst, and returndst.C reference: memcpy(3).
The two regions must not overlap;
memmovecopies between overlapping regions. The caller keeps both regions alive during the call.
- numbox.core.bindings.libc.memmove(dst, src, n)[source]
Copy
nbytes from addresssrcto addressdst, which may overlap, and returndst.C reference: memmove(3).
The caller keeps both regions alive during the call.
- numbox.core.bindings.libc.memset(dst, c, n)[source]
Fill the
nbytes at addressdstwithc, converted tounsigned char, and returndst.C reference: memset(3).
- numbox.core.bindings.libc.putchar(c)[source]
Write
c, converted tounsigned char, to C’s stdout, and return the byte written.C reference: putchar(3).
The result is
EOFon error.
- numbox.core.bindings.libc.puts(s)[source]
Write the NUL-terminated string at address
sand a newline to C’s stdout.C reference: puts(3).
The result is non-negative on success and
EOFon error.sis anintpaddress that the caller keeps alive during the call.
- numbox.core.bindings.libc.rand()[source]
Return the next pseudo-random integer, from 0 to
RAND_MAX, of the generator thatsrandseeds.C reference: rand(3).
RAND_MAXis 2147483647 with glibc and on macOS, and 32767 on Windows. C does not requirerandto be safe to call from several threads concurrently.
- numbox.core.bindings.libc.srand(s)[source]
Seed the generator that
randuses withs.C reference: srand(3).
C takes the seed as an
unsigned int: numba converts an integer argument toint32without a warning, and C reads its 32 bits as unsigned.
- numbox.core.bindings.libc.strchr(s, c)[source]
Return the address of the first byte equal to
cin the NUL-terminated string ats, or 0 if none.C reference: strchr(3).
C converts
ctochar, and acof 0 finds the terminating NUL. numba converts an integer argument toint32without a warning.
- numbox.core.bindings.libc.strcmp(a, b)[source]
Compare the NUL-terminated strings at addresses
aandbbyte by byte, as unsigned bytes.C reference: strcmp(3).
The result is negative if
asorts first, 0 if the strings are equal, and positive ifbsorts first.
- numbox.core.bindings.libc.strerror(errnum)[source]
Return the address of the message string for the error number
errnum.C reference: strerror(3).
C does not require
strerrorto be thread-safe: the string may be in a buffer that a later call overwrites.strerror_safe()writes the message into the caller’s buffer instead.
- numbox.core.bindings.libc.strlen(s)[source]
Return the number of bytes in the NUL-terminated string at address
s, the NUL excluded.C reference: strlen(3).
sis anintpaddress, such as one fromget_unicode_data_p(), and the caller keeps the string alive during the call.
- numbox.core.bindings.libc.strncmp(a, b, n)[source]
Compare at most the first
nbytes of the NUL-terminated strings at addressesaandb.C reference: strncmp(3).
The comparison stops at the first NUL in either string, and the result follows the sign convention of
strcmp. Annof 0 gives 0.
- numbox.core.bindings.libc.strncpy(dst, src, n)[source]
Copy at most
nbytes of the NUL-terminated string atsrctodst, and returndst.C reference: strncpy(3).
If
srcis shorter thannbytes, C fills the rest of thenbytes with NULs. If it isnbytes or longer,dstreceivesnbytes and no terminating NUL. A caller that needs a NUL-terminated result reserves one more byte, and either zeroes the buffer first or writes a NUL at offsetnofdstafter the call.
- numbox.core.bindings.libc.strrchr(s, c)[source]
Return the address of the last byte equal to
cin the NUL-terminated string ats, or 0 if none.C reference: strrchr(3).
C converts
ctochar, and acof 0 finds the terminating NUL. numba converts an integer argument toint32without a warning.
numbox.core.bindings.libm
Bindings for the functions of the C math library, on float64.
Each binding calls the double form of the C function of its name, so it takes and returns float64, and numba
converts an integer or float32 argument without a warning. The bindings behave as C’s functions, not Python’s. C
returns NaN or an infinity where Python’s math module raises ValueError or OverflowError, as for
sqrt(-1.0), log(0.0) or exp(1000.0), and round and pow differ from Python’s built-ins. Import the
module, as in from numbox.core.bindings import libm, and call libm.round, so that the name round still
refers to Python’s built-in function. numba registers 26 of these names, among them cos, pow and sqrt, for
its own math support, and LLVM finds a registered name before it searches any library. On Windows, those 26 bindings
therefore call the functions of CPython’s C runtime instead of those of the msvcrt.dll that this module loads for
"m".
- numbox.core.bindings.libm.acos(x)[source]
Return the arc cosine of
xin radians, from 0 to pi.C reference: acos(3).
An
xoutside [-1, 1] gives NaN. The binding calls C’sdoubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one inmsvcrt.dll, because numba registers the nameacosfor its own math support.
- numbox.core.bindings.libm.acosh(x)[source]
Return the inverse hyperbolic cosine of
x, a value of 0 or more.C reference: acosh(3).
An
xbelow 1 gives NaN. The binding calls C’sdoubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one inmsvcrt.dll, because numba registers the nameacoshfor its own math support.
- numbox.core.bindings.libm.asin(x)[source]
Return the arc sine of
xin radians, from -pi/2 to pi/2.C reference: asin(3).
An
xoutside [-1, 1] gives NaN. The binding calls C’sdoubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one inmsvcrt.dll, because numba registers the nameasinfor its own math support.
- numbox.core.bindings.libm.asinh(x)[source]
Return the inverse hyperbolic sine of
x.C reference: asinh(3).
The binding calls C’s
doubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one inmsvcrt.dll, because numba registers the nameasinhfor its own math support.
- numbox.core.bindings.libm.atan(x)[source]
Return the arc tangent of
xin radians, from -pi/2 to pi/2.C reference: atan(3).
The binding calls C’s
doubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one inmsvcrt.dll, because numba registers the nameatanfor its own math support.
- numbox.core.bindings.libm.atan2(y, x)[source]
Return the arc tangent of
y / xin radians, in the quadrant that the signs ofxandydetermine.C reference: atan2(3).
The result is in the range from -pi to pi, and the first argument is
y, as in C. The binding calls C’sdoubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one inmsvcrt.dll, because numba registers the nameatan2for its own math support.
- numbox.core.bindings.libm.atanh(x)[source]
Return the inverse hyperbolic tangent of
x.C reference: atanh(3).
An
xof 1 or -1 gives an infinity of the same sign, and anxoutside [-1, 1] gives NaN. The binding calls C’sdoubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one inmsvcrt.dll, because numba registers the nameatanhfor its own math support.
- numbox.core.bindings.libm.cbrt(x)[source]
Return the cube root of
x, which is negative for a negativex.C reference: cbrt(3).
The binding calls C’s
doubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning.
- numbox.core.bindings.libm.ceil(x)[source]
Return the smallest integral value that is not less than
x, as a float.C reference: ceil(3).
The binding calls C’s
doubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one inmsvcrt.dll, because numba registers the nameceilfor its own math support.
- numbox.core.bindings.libm.copysign(x, y)[source]
Return a value with the magnitude of
xand the sign ofy.C reference: copysign(3).
The binding calls C’s
doubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning.
- numbox.core.bindings.libm.cos(x)[source]
Return the cosine of
x, an angle in radians.C reference: cos(3).
The binding calls C’s
doubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one inmsvcrt.dll, because numba registers the namecosfor its own math support.
- numbox.core.bindings.libm.cosh(x)[source]
Return the hyperbolic cosine of
x.C reference: cosh(3).
The binding calls C’s
doubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one inmsvcrt.dll, because numba registers the namecoshfor its own math support.
- numbox.core.bindings.libm.erf(x)[source]
Return the error function of
x.C reference: erf(3).
The binding calls C’s
doubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning.
- numbox.core.bindings.libm.erfc(x)[source]
Return the complementary error function of
x,1 - erf(x), computed accurately for largex.C reference: erfc(3).
The binding calls C’s
doubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning.
- numbox.core.bindings.libm.exp(x)[source]
Return e raised to the power
x.C reference: exp(3).
The binding calls C’s
doubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one inmsvcrt.dll, because numba registers the nameexpfor its own math support.
- numbox.core.bindings.libm.exp2(x)[source]
Return 2 raised to the power
x.C reference: exp2(3).
The binding calls C’s
doubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning.
- numbox.core.bindings.libm.expm1(x)[source]
Return e raised to the power
x, minus 1, computed accurately whenxis near 0.C reference: expm1(3).
The binding calls C’s
doubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one inmsvcrt.dll, because numba registers the nameexpm1for its own math support.
- numbox.core.bindings.libm.fabs(x)[source]
Return the absolute value of
x.C reference: fabs(3).
The binding calls C’s
doubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one inmsvcrt.dll, because numba registers the namefabsfor its own math support.
- numbox.core.bindings.libm.fdim(x, y)[source]
Return
x - yifxis greater thany, and 0 otherwise.C reference: fdim(3).
The binding calls C’s
doubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning.
- numbox.core.bindings.libm.floor(x)[source]
Return the largest integral value that is not greater than
x, as a float.C reference: floor(3).
The binding calls C’s
doubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one inmsvcrt.dll, because numba registers the namefloorfor its own math support.
- numbox.core.bindings.libm.fmax(x, y)[source]
Return the larger of
xandy; if one of them is NaN, return the other.C reference: fmax(3).
The binding calls C’s
doubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning.
- numbox.core.bindings.libm.fmin(x, y)[source]
Return the smaller of
xandy; if one of them is NaN, return the other.C reference: fmin(3).
The binding calls C’s
doubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning.
- numbox.core.bindings.libm.fmod(x, y)[source]
Return
x - n * y, wherenisx / yrounded toward zero, so the result has the sign ofx.C reference: fmod(3).
Python’s
%gives the result the sign ofyinstead. Ayof 0 gives NaN. The binding calls C’sdoubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one inmsvcrt.dll, because numba registers the namefmodfor its own math support.
- numbox.core.bindings.libm.hypot(x, y)[source]
Return the square root of
x * x + y * y, without overflow or underflow in the intermediate steps.C reference: hypot(3).
The binding calls C’s
doubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning.
- numbox.core.bindings.libm.lgamma(x)[source]
Return the natural logarithm of the absolute value of the gamma function at
x.C reference: lgamma(3).
The sign of the gamma function is not returned: C stores it in the global variable
signgam, which numbox does not read. Because of that global variable, C does not requirelgammato be thread-safe. The binding calls C’sdoubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning.
- numbox.core.bindings.libm.log(x)[source]
Return the natural logarithm of
x.C reference: log(3).
An
xof 0 gives negative infinity, and a negativexgives NaN. The binding calls C’sdoubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one inmsvcrt.dll, because numba registers the namelogfor its own math support.
- numbox.core.bindings.libm.log10(x)[source]
Return the base-10 logarithm of
x.C reference: log10(3).
An
xof 0 gives negative infinity, and a negativexgives NaN. The binding calls C’sdoubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one inmsvcrt.dll, because numba registers the namelog10for its own math support.
- numbox.core.bindings.libm.log1p(x)[source]
Return the natural logarithm of
1 + x, computed accurately whenxis near 0.C reference: log1p(3).
An
xof -1 gives negative infinity, and anxbelow -1 gives NaN. The binding calls C’sdoubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one inmsvcrt.dll, because numba registers the namelog1pfor its own math support.
- numbox.core.bindings.libm.log2(x)[source]
Return the base-2 logarithm of
x.C reference: log2(3).
An
xof 0 gives negative infinity, and a negativexgives NaN. The binding calls C’sdoubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning.
- numbox.core.bindings.libm.logb(x)[source]
Return the base-2 exponent of
xas a float:floor(log2(abs(x)))for a finitexother than 0.C reference: logb(3).
An
xof 0 gives negative infinity. The binding calls C’sdoubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning.
- numbox.core.bindings.libm.nearbyint(x)[source]
Return
xrounded to an integral value in the current rounding mode, as a float.C reference: nearbyint(3).
It differs from
rintonly in that it does not set C’s inexact floating-point exception flag. In the default mode, a halfway case goes to the even value. The binding calls C’sdoubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning.
- numbox.core.bindings.libm.pow(x, y)[source]
Return
xraised to the powery.C reference: pow(3).
This is C’s
pow, not Python’s: a negativexwith a non-integralygives NaN, and 0 with a negativeygives infinity, where Python’s**gives a complex number or raisesZeroDivisionError. The binding calls C’sdoubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one inmsvcrt.dll, because numba registers the namepowfor its own math support.
- numbox.core.bindings.libm.remainder(x, y)[source]
Return
x - n * y, wherenisx / yrounded to the nearest integer, halfway cases to even.C reference: remainder(3).
This is the IEEE 754 remainder:
remainder(7.0, 2.0)is -1.0. Ayof 0 gives NaN. The binding calls C’sdoubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning.
- numbox.core.bindings.libm.rint(x)[source]
Return
xrounded to an integral value in the current rounding mode, as a float.C reference: rint(3).
In the default mode, which rounds to nearest, a halfway case goes to the even value:
rint(2.5)is 2.0. The binding calls C’sdoubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning.
- numbox.core.bindings.libm.round(x)[source]
Return
xrounded to the nearest integral value, with halfway cases away from zero, as a float.C reference: round(3).
This is C’s
round, not Python’s:round(2.5)is 3.0 here and 2 in Python. The binding calls C’sdoubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one inmsvcrt.dll, because numba registers the nameroundfor its own math support.
- numbox.core.bindings.libm.sin(x)[source]
Return the sine of
x, an angle in radians.C reference: sin(3).
The binding calls C’s
doubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one inmsvcrt.dll, because numba registers the namesinfor its own math support.
- numbox.core.bindings.libm.sinh(x)[source]
Return the hyperbolic sine of
x.C reference: sinh(3).
The binding calls C’s
doubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one inmsvcrt.dll, because numba registers the namesinhfor its own math support.
- numbox.core.bindings.libm.sqrt(x)[source]
Return the square root of
x.C reference: sqrt(3).
A negative
xgives NaN. The binding calls C’sdoubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one inmsvcrt.dll, because numba registers the namesqrtfor its own math support.
- numbox.core.bindings.libm.tan(x)[source]
Return the tangent of
x, an angle in radians.C reference: tan(3).
The binding calls C’s
doubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one inmsvcrt.dll, because numba registers the nametanfor its own math support.
- numbox.core.bindings.libm.tanh(x)[source]
Return the hyperbolic tangent of
x.C reference: tanh(3).
The binding calls C’s
doubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one inmsvcrt.dll, because numba registers the nametanhfor its own math support.
- numbox.core.bindings.libm.tgamma(x)[source]
Return the gamma function at
x.C reference: tgamma(3).
The binding calls C’s
doubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning.
- numbox.core.bindings.libm.trunc(x)[source]
Return
xrounded toward zero to an integral value, as a float.C reference: trunc(3).
The binding calls C’s
doubleform, so it takes and returnsfloat64, and numba converts an integer orfloat32argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one inmsvcrt.dll, because numba registers the nametruncfor its own math support.
numbox.core.bindings.stdio
The C standard streams, stdout, stderr and stdin, as FILE * values for jitted code and Python.
stdout(), stderr() and stdin() return the running process’s three streams as intp addresses,
which C functions such as fputs, fflush and fprintf take. Each call reads the address in the running
process, so a cached caller never uses an address from the process that compiled it. On Windows, the functions need the
Universal C Runtime (UCRT) of Windows 10 and later. Older Windows versions name the streams _iob or __iob_func,
differently in each Visual C++ runtime, and numbox does not support them.
- numbox.core.bindings.stdio.stderr()[source]
Return the running process’s C stream
stderr, aFILE *, as anintp.C reference: stderr(3).
Each call reads the address in the running process. C writes
stderrwithout a buffer on Linux. On Windows, C buffers astderrthat goes to a file or a pipe, so callfflush(stderr())there.
- numbox.core.bindings.stdio.stdin()[source]
Return the running process’s C stream
stdin, aFILE *, as anintp.C reference: stdin(3).
Each call reads the address in the running process.
- numbox.core.bindings.stdio.stdout()[source]
Return the running process’s C stream
stdout, aFILE *, as anintp.C reference: stdout(3).
Each call reads the address in the running process. C buffers this stream separately from Python’s
sys.stdout, so flush both, withfflush(stdout())andsys.stdout.flush(), to make jitted output and Python output appear in the order in which they were written.
numbox.core.bindings.errno
Reading and setting the calling thread’s errno, from jitted code and from Python.
errno_get() returns the current thread’s errno and
errno_set() sets it. Both call the C library’s accessor on every use, so each reads or
writes the errno of the thread that runs it.
- numbox.core.bindings.errno.errno_get()[source]
Return the calling thread’s
errnoas anint32.C reference: errno(3).
Each call looks up the errno of the thread that runs it, so an iteration of a
prangeloop reads the errno of its own thread. A Python caller reads the errno that a jitted function set on the same thread. After a parallel loop, the calling thread’s errno depends on numba’s threading layer. Under OpenMP, the calling thread runs some iterations itself, and its errno holds the value that those iterations set. Under the workqueue layer, the calling thread runs no iterations, and its errno is unchanged.
numbox.core.bindings.strerror
A thread-safe message for an error number, for jitted code and Python.
strerror_safe() writes the message for an error number into a buffer that the caller provides. It calls the
thread-safe form of strerror that the platform’s C library exports, chosen when numba compiles the call:
glibc: __xpg_strerror_r, the POSIX (XSI) form, which glibc exports from version 2.3.4, released in 2004;
musl: also
__xpg_strerror_r, which musl exports as a weak alias of itsstrerror_r, itself the POSIX form;macOS: strerror_r, the POSIX form;
Windows: strerror_s, which takes its arguments in the order buffer, size, error number.
numbox supports no other C library on Linux. glibc’s plain strerror_r is the GNU form, which returns a char *
and does not match the POSIX-shaped call that this module emits. The module therefore calls __xpg_strerror_r on
Linux whenever LLVM finds it, as it does with glibc and musl, and falls back to strerror_r only for a C library that
lacks the symbol.
- numbox.core.bindings.strerror.strerror_safe(errnum, buf, buflen)[source]
Write the message for the error number
errnuminto the buffer atbuf, and return 0 or an error number.C reference: strerror_r(3).
bufis theintpaddress ofbuflenbytes that the caller keeps alive during the call, and the message ends with a NUL. The binding narrowserrnumtoint32, the width of C’sint. With glibc, the function returnsEINVAL(22) for an unknown number and writesUnknown errorfollowed by the number. It returnsERANGE(34) for a buffer too short for the message and writes as much of the message as fits. The function uses no buffer of its own, so threads can call it at the same time. On Linux it calls__xpg_strerror_r, which glibc and musl export, on macOSstrerror_r, and on Windowsstrerror_s, with the arguments in that function’s order.
numbox.core.bindings.fmtio
C’s printf, fprintf, snprintf and sscanf, for Python and for jitted code.
The four public functions are ordinary Python functions that take C’s arguments in C’s order, with the values after the
format as separate arguments, not in a tuple. In jitted code, numba compiles each call, through an @overload, into a
call of the C function of the same name, with the format embedded as a constant. printf(), fprintf() and
snprintf() run from the same source under Python and in jitted code: Python’s % operator formats the text
under Python, and C formats it in jitted code. sscanf() runs in jitted code only. numba compiles a jitted call
into its caller’s code. A caller cached with cache=True therefore runs the fmtio code of the numbox version that
compiled it, as the section “Caching callers of the formatted I/O functions” of the bindings page explains. The section
“Formatted output and input” there describes the conversions, where Python’s output and C’s differ, snprintf’s
truncation and sscanf’s storage. The rest of the module is private: the intrinsics that emit the C calls, and the
checks that numbox runs on a format when numba compiles a call.
- numbox.core.bindings.fmtio.fprintf(fp, fmt, *args)[source]
Format
argsbyfmt, write the text to the streamfp, and return the number of bytes written.C reference: fprintf(3).
fpis aFILE *as anintp, such as one thatstdout()orfopenreturns. The format and the arguments follow the rules ofprintf(), in both modes. In jitted code, numba compiles the call into a call of C’sfprintf, which accepts anyFILE *.Under Python, the function writes to
sys.stdout,sys.stderrorsys.stdinfor the address of the matching C stream, and flushes it. It raisesRuntimeErrorfor any otherFILE *, such as one fromfopen; use Python’sopenandwritefor a file there. The function maps the three addresses to thesysobjects that are current at its first call, so a redirection installed after that call does not change where it writes. WithNUMBA_DISABLE_JIT=1, the first call raisesAttributeError, because it imports the stdio bindings.
- numbox.core.bindings.fmtio.printf(fmt, *args)[source]
Format
argsby the C format stringfmt, write the text to stdout, and return the number of bytes written.C reference: printf(3).
Under Python,
fmtcan be anystr. The function formats with Python’s%operator, writes the text to the currentsys.stdoutand flushes it, and returns the length in bytes of the text in UTF-8. Python’s%ignores the length modifiersh,landLand rejects the others, such as thellof%lld, so the function removes every length modifier before it formats. It also removes one that follows a literal%%, so"%%lld"prints%dunder Python.%pworks only in jitted code, because Python’s%rejects it.%sgiven an address prints the number under Python, where C prints the string at that address.In jitted code, numba compiles the call into a call of C’s
printf, which writes to C’s stdout and returns anint32.fmtmust be a string that numba reads as a constant, such as a literal, and C receives it in UTF-8. numbox checks the conversions against the arguments when numba compiles the call, as GCC’s-Wformatdoes, and raisesTypingErrorfor a mismatch. numbox passes astrargument to C as the address of its characters, which C reads as text only for an ASCII string. The check is applied to that address, so astrgiven to%dcompiles and prints the address. numbox passes every integer andboolto C as 64 bits and every float as afloat64, and C converts each value to the type that its conversion names, such asintfor%d. On Windows, C’slonghas 32 bits, so use%lldrather than%ldfor anint64. A width such as%-10scounts bytes, not characters; to pad by characters, pad the string first, for example withstr.ljust.In both modes,
%nand the'flag raise an error:TypingErrorin jitted code andValueErrorunder Python.
- numbox.core.bindings.fmtio.snprintf(buf_p, size, fmt, *args)[source]
Format
argsbyfmtinto thesizebytes at addressbuf_p, and return the length of the whole text.C reference: snprintf(3).
buf_pis theintpaddress of at leastsizebytes, such asarray_data_p(buf), which the caller keeps alive during the call. The function writes at mostsizebytes, the terminating NUL included, and returns the length in bytes of the text without the NUL, so a result ofsizeor more means that it truncated the text. The format and the arguments follow the rules ofprintf().In jitted code,
buf_pandsizemust beintpvalues:a.size,np.intp(16)and anint64argument of the jitted function work, but a literal such as16and annp.int32fail to compile withTypingError. On Windows, jitted code calls C’s _snprintf instead. It returns -1 when the text is longer thansize, and when the text is exactlysizebytes long, it returnssizeand writes no NUL. The testn < 0 or n >= sizecovers both cases on every platform.Under Python, the function follows the C99 rule on every platform.
ctypes.memmovewrites the text, and it rejects a NumPy integer asbuf_p.array_data_preturns one underNUMBA_DISABLE_JIT=1, so passint(array_data_p(buf))there.
- numbox.core.bindings.fmtio.sscanf(buf, fmt, *args)[source]
Read values by
fmtfrom the NUL-terminated text at addressbufinto storage, in jitted code only.C reference: sscanf(3).
The result is the number of values stored, or -1, C’s
EOF, if the text ends before the first conversion.bufis theintpaddress of the text, such asget_unicode_data_p(text)for an ASCIIstr. Each argument afterfmtis theintpaddress of the storage for one conversion, such asarray_data_pof a one-element array of the matching dtype. numbox checks only that each of them is anintp. It does not compare the format with the arguments, so the caller must make them match in number and in size.fmtmust be a string that numba reads as a constant, as forprintf(). Under Python, the function raisesNotImplementedError; useint(),float()orreto parse the text there.
numbox.core.bindings.abi
The C calling-convention rules that the bindings’ internal helper applies to each call.
numbox.core.bindings.call._call_lib_func uses this module to determine the calling convention that the host follows
and the class of each value in a call: a number or a pointer, a struct of 16 bytes or less, or a larger struct. The
module computes the size of a struct written as a numba tuple or record, and the offset of each field, as a C compiler
lays them out. For a 16-byte struct, the module computes the class of each 8-byte half, and those classes determine
whether the helper repacks the struct before the call. Every name in the module is private to the bindings.
numbox.core.bindings.call
The internal helper through which the libc, libm and SQLite bindings call C functions.
_call_lib_func is a numba intrinsic that compiles a call of a C function by its name. It takes the result type from
numbox.core.bindings.signatures, checks that LLVM can find the name, and passes each value by the host’s calling
convention, which numbox.core.bindings.abi classifies. numbox’s bindings call it from functions decorated with
proxy(), so that numba has converted the arguments to the table’s types first.
_call_lib_func_byval passes a struct through a pointer to a copy, for a C function that takes a pointer to a
struct. The section “Passing a struct” of the bindings page says which structs reach C intact.
numbox.core.bindings.signatures
The table of C signatures that the libc, libm and SQLite bindings use, keyed by the C function’s name.
signatures merges signatures_c for the C standard library, signatures_m for the C math library and
signatures_sqlite for SQLite. Each value is the numba signature of the C function. C’s int is int32, a
64-bit integer such as long long or sqlite3_int64 is int64, and double is float64. An unsigned type
is the unsigned numba type of the same width, and size_t and every pointer are intp. Each binding is compiled
for its entry, and _call_lib_func takes the result type from it. The table holds no C long, whose width is 64
bits on Linux and macOS and 32 bits on Windows. lldiv_t is the tuple type of the result of C’s lldiv.
numbox.core.bindings.utils
Library loading and small helpers for the binding modules.
load_lib() and load_lib_path() load a C library so that LLVM finds its symbols when it links jitted code
into the process. extract_literal_str() reads the value of a numba string literal, such as a format string or a C
function’s name, and intp_ll_type() returns the LLVM type that numbox uses for size_t and pointers.
platform_ holds the name of the operating system, as platform.system() returns it.
- numbox.core.bindings.utils.extract_literal_str(binding_name, ty, *, field='argument')[source]
Return the
strvalue of a numba string literal type.Intrinsics and overloads use it for an argument that numba must know when it compiles the call, such as a format string, a C function’s name or a standard stream’s name. It raises
TypingErroriftyis not a literal or if its value is not astr, and the message namesbinding_nameand the argument,field.
- numbox.core.bindings.utils.intp_ll_type(context=None)[source]
Return the LLVM integer type of numba’s
intp, which numbox uses forsize_tand pointers.With a codegen
context, the type iscontext.get_value_type(intp), which is how an intrinsic derives a width that depends on the platform, such as that ofsize_t,ssize_torptrdiff_t. Without one, as in a test or an IR probe, it isllir.IntType(intp.bitwidth). numba lowersintpto an integer of that same width, so both calls give the same type.
- numbox.core.bindings.utils.load_lib(name)[source]
Return the
ctypes.CDLLhandle of the library whose short name isname, loading it at the first call.The first call loads the library so that LLVM finds its symbols, and later calls with the same name return the same handle from the module’s cache,
_loaded_libs. Each binding module calls it for its own library, and the modules share the handle without importing one another. A caller can test for a symbol withhasattr(handle, name), asproxy_if_available()does. ctypes never unloads a library, so the library stays loaded for the life of the process.On Linux and macOS,
ctypes.util.find_libraryfinds the file by the short name, such as"m"for the C math library, in the system’s library search and not in the Python installation. The file is then opened in global symbol mode,RTLD_GLOBAL. On Windows, the function loads the C runtimemsvcrt.dllfor"c"and"m", and only thesqlite3.dllbundled with Python for"sqlite3". For any other name, it prefers a DLL bundled with Python to one on thePATH.If no file is found, the function raises
RuntimeError: Could not find shared library for <name>; pass the file’s path toload_lib_path()instead. On Linux,find_libraryalso searches the directories inLD_LIBRARY_PATH, but it finds a library there only if the library was built with a SONAME, and the system’s loader reads the variable only when the process starts. On macOS,find_librarysearches the directories inDYLD_LIBRARY_PATHasos.environholds the variable at the call.
- numbox.core.bindings.utils.load_lib_path(path)[source]
Load the library at
pathso that LLVM finds its symbols, and return a newctypes.CDLLhandle.pathis any string thatctypes.CDLLaccepts: an absolute path, a soname such aslibm.so.6, whichctypes.util.find_libraryreturns, or a file name that the system’s loader resolves. The function opens the library withRTLD_GLOBALon Linux and macOS and withwinmode=0on Windows, and it raisesRuntimeErroron any other platform. Each call returns a new handle; useload_lib()for a library that several modules load by its short name.