diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..81faab7 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.15...3.26) +project(${SKBUILD_PROJECT_NAME} LANGUAGES C) + +message(STATUS "CMAKE_BUILD_TYPE set to '${CMAKE_BUILD_TYPE}'") + +# Source code +file(GLOB _pointers_SRC + ${CMAKE_CURRENT_SOURCE_DIR}/src/_pointers/*.c +) +MESSAGE(DEBUG ${_pointers_SRC}) + +# Find Python +find_package( + Python + COMPONENTS Interpreter Development.Module + REQUIRED) + +# Link Python +python_add_library(_pointers MODULE ${_pointers_SRC} WITH_SOABI) + +# Add include directories +target_include_directories(_pointers PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include/) + +MESSAGE(STATUS "Everything looks good, let's install!") +# Install extension module +install(TARGETS _pointers DESTINATION .) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 169d2f7..0000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,10 +0,0 @@ -# Contribution - -If you would like to contribute to pointers.py, just make a pull request with your changes. - -Any pull request should include the following: - -- Type safe and provides type annotations -- PEP 8 compliant code -- Passes tests specified in the [tests](https://github.com/ZeroIntensity/pointers.py/tree/master/tests) directory -- Documentation updated accordingly diff --git a/_pointers.pyi b/_pointers.pyi new file mode 100644 index 0000000..bd61d30 --- /dev/null +++ b/_pointers.pyi @@ -0,0 +1,8 @@ +from typing import Any + +def deref(address: int, /) -> Any: ... +def decref(obj: Any, /) -> None: ... +def incref(obj: Any, /) -> None: ... +def setref(obj: Any, refcount: int, /) -> None: ... +def getref(obj: Any, /) -> int: ... +def setimmortal(obj: Any, /) -> None: ... diff --git a/compile_flags.txt b/compile_flags.txt index 00c4209..3cb5819 100644 --- a/compile_flags.txt +++ b/compile_flags.txt @@ -1,2 +1,2 @@ -I -/usr/include/python3.8 +/usr/include/python3.12 diff --git a/docs/allocation.md b/docs/allocation.md deleted file mode 100644 index 415ce48..0000000 --- a/docs/allocation.md +++ /dev/null @@ -1,196 +0,0 @@ -# Allocation - -## Basics - -We can use memory functions (`malloc`, `free`, `calloc`, `realloc`) the same way you would use them in C, and use them via the pointer API. - -Here's an example: - -```py -from pointers import malloc, free - -ptr = malloc(28) # 28 is the size of integers larger than 0 -free(ptr) -``` - -We can dereference the same way we did earlier, but first, we need to actually put something in the memory. We can do this via data movement: - -```py -from pointers import malloc, free - -ptr = malloc(28) -ptr <<= 1 -print(*ptr) -free(ptr) -``` - -Data movement is much safer when using memory allocation, since we aren't actually overwriting memory tracked by Python. - -We also aren't overwriting any existing objects, we are just putting the object into a memory space. - -Here's a quick example: - -```py -from pointers import malloc, free - -ptr = malloc(28) -ptr <<= 1 -print(*ptr) -ptr <<= 2 -print(*ptr, 1) # prints out "2 1", since we dont have to overwrite the 1 object itself! -free(ptr) -``` - -We can bypass size limits the same way as before, but again, this is extremely discouraged. Instead, we should use `realloc`. - -## Reallocation - -The `realloc` function works a bit differently in pointers.py. We don't reassign the pointer like you would in C: - -```py -ptr = realloc(ptr, 28) -``` - -Instead, we can just call `realloc` on the object directly, like so: - -```py -from pointers import malloc, realloc, free - -ptr = malloc(24) -ptr <<= 0 -realloc(ptr, 28) -free(ptr) -``` - -## Identity - -Identity of objects in CPython are defined by their memory address, so using `is` on objects inside allocated memory won't work properly: - -```py -from pointers import malloc, free -import sys - -text: str = "hello world" -ptr = malloc(sys.getsizeof(text)) -ptr <<= text -print(~ptr is text) # False -``` - -## Arrays - -We can allocate an array using `calloc`: - -```py -from pointers import calloc, free - -ptr = calloc(4, 28) # allocate an array of 4 slots of size 28 -``` - -You can (somewhat) use an allocated array as you would in C: - -```py -from pointers import calloc, free - -array = calloc(4, 28) - -for index, ptr in enumerate(array): - ptr <<= index - -print(ptr[1]) # prints out "1" -``` - -## Stack - -Objects can be put on the stack using `stack_alloc` or `acquire_stack_alloc`: - -```py -from pointers import stack_alloc, StackAllocatedPointer - -@stack_alloc(28) -def test(ptr: StackAllocatedPointer): - ptr <<= 1 - print(*ptr) - -test() -``` - -The difference between `acquire_stack_alloc` and `stack_alloc` is that `acquire_stack_alloc` automatically calls the function, whereas `stack_alloc` makes you call it manually: - -```py -from pointers import stack_alloc, acquire_stack_alloc, StackAllocatedPointer - -@stack_alloc(28) -def a(ptr: StackAllocatedPointer): # you need to call a manually - ... - -@acquire_stack_alloc(28) -def b(ptr: StackAllocatedPointer): # this is called automatically by the decorator - ... -``` - -Stack allocated pointers **cannot** be deallocated manually, meaning the following **will not** work: - -```py -from pointers import acquire_stack_alloc, StackAllocatedPointer, free - -@acquire_stack_alloc(28) -def test(ptr: StackAllocatedPointer): - free(ptr) # ValueError is raised -``` - -Instead, it will be popped off the stack at the end of the function. Read more about that below. - -### Why not a context? - -**Warning:** This section is for advanced users. - -We have to go through a couple different reasons on why we need to use a decorator instead of a context for stack allocations. - -First, we need to understand how functions are handled in ASM (at least on GNU compilers). - -Lets take a look at this piece of x86 ASM as an example (32 bit): - -```asm -global _start - -_start: - push 123 ; 123 on stack - call func ; call our function - mov eax, 1 ; system exit - mov ebx, 0 ; return code - int 0x80 ; call kernel - -func: - push ebp ; push base pointer onto the stack - mov ebp, esp ; preserve current stack top - - mov esp, ebp - pop ebp ; restore base pointer - ret ; jump to return address -``` - -This function does nothing, but as you can see with the `push` and `pop` instructions, we are using the stack to pass parameters and store the return address of the functions. - -When we put something on the top of the stack in Python, we still need to follow these rules. The memory is popped off the stack at the end of the C function (in this case, its pointers.py's `run_stack_callback`), so we cannot use it elsewhere. - -Now, how does this relate to using a context or not? - -Python context managers are done like this: - -```py -class MyContext: - def __enter__(self): - ... - - def __exit__(self, *_): - ... - -with MyContext() as x: - ... -``` - -Remember, the data is popped off the stack after the end of the C function, not the Python function, meaning we can't just allocate and then store in the class. We also can't just do it all from `__enter__`, since the allocated memory will be destroyed at the end of it. - -We also can't do it from a C based class, since that will still have to return the object. - -Note that there's also no yielding in C, so we can't return early either. diff --git a/docs/bindings.md b/docs/bindings.md deleted file mode 100644 index cfb5241..0000000 --- a/docs/bindings.md +++ /dev/null @@ -1,303 +0,0 @@ -# C Bindings - -Pointers.py provides type safe bindings for most of the C standard library. We can use one by just importing it: - -```py -from pointers import printf - -printf("hello world\n") -``` - -## Collisions - -Some names are either already used by python or used by pointers.py, so they are prefixed with `c_`. - -For example, `raise` and `malloc` are both used, so you can import their bindings by importing `c_raise` and `c_malloc`: - -```py -from pointers import c_raise, c_malloc - -# ... -``` - -## Pointers - -Several things in the C standard library require pointers. To create your own, you can use `to_c_ptr`: - -```py -from pointers import to_c_ptr - -ptr = to_c_ptr(1) # creates a pointer to the c integer 1 -``` - -Then, we can just pass it to the binding: - -```py -from pointers import to_c_ptr, time - -ptr = to_c_ptr(1) -time(ptr) -print(time) # unix timestamp -``` - -### Strings - -`to_c_ptr` automatically converts the passed type to a C type, but that can be misleading with strings. - -When you pass a `str`, pointers.py has to convert it to a `wchar_t*`, not `char*`. - -If you want a `char*`, you need to pass a `bytes` object: - -```py -from pointers import to_c_ptr - -wcharp = to_c_ptr("test") # wchar_t* -charp = to_c_ptr(b"test") # char* -``` - -This **is not** the same for the bindings though. Pointers.py is able to convert a `str` to `char*` just fine: - -```py -from pointers import puts - -puts("a") # no need for a bytes object here -``` - -**Note:** Any pointer object that derives from `BaseCPointer` may be passed to a binding. Otherwise, you have to manually convert it. - -## Void Pointers - -Some types cannot be convert to a Python type or they can point to anything. For this, pointers.py uses the `VoidPointer` class: - -```py -from pointers import c_malloc - -ptr = c_malloc(0) # ptr gets assigned to VoidPointer -``` - -`FILE*` is an example of a type that can't be converted: - -```py -from pointers import fopen, fprintf, fclose - -file = fopen("/dev/null", "w") # assigns to the c FILE* type -fprintf(file, "hello world") -fclose(file) -``` - -You can pass void pointers the same way: - -```py -from pointers import c_malloc, printf - -ptr = c_malloc(0) -printf("%p\n", ptr) -``` - -If you try and derefernce a void pointer, it just returns its memory address: - -```py -from pointers import c_malloc - -ptr = c_malloc(0) -print(*ptr) -``` - -### Casting - -`VoidPointer` objects can be casted to a typed pointer with the `cast` function, like so: - -```py -from pointers import c_malloc, printf, cast, strcpy, c_free - -ptr = c_malloc(3) -strcpy(ptr, "hi") -printf("%s\n", cast(ptr, bytes)) # bytes refers to char*, str refers to wchar_t* -c_free(ptr) -``` - -You can even dereference a casted `VoidPointer` to get its actual value: - -```py -ptr = c_malloc(3) -strcpy(ptr, "hi") -print(*cast(ptr, bytes)) # b'hi' -c_free(ptr) -``` - -## Structs - -Some bindings, such as `div` return a struct. For this, pointers.py has its own `Struct` class: - -```py -from pointers import div - -a = div(10, 1) # type is DivT, which inherits from Struct -print(a.quot) # prints out 10 -``` - -## Functions - -There are a few bindings which require a function. All you have to do is write a function, and then pass it to the binding: - -```py -from pointers import c_raise, signal, exit - -def sighandler(signum: int): - print(f"handling signal {signum}") - exit(0) - -signal(2, sighandler) -c_raise(2) # send signal 2 to the program -``` - -Alternatively, you can create a function pointer using `to_func_ptr`: - -```py -from pointers import to_func_ptr, signal, exit, c_raise - -def test(signum: int) -> None: - print('hello world') - exit(0) - -signal(2, to_func_ptr(test)) -c_raise(2) -``` - -**Note:** `to_func_ptr` requires the function to be type hinted in order to correctly generate the signature of the C function, so the following **will not** work: - -```py -def test(signum): - ... - -to_func_ptr(test) -``` - -## Null Pointers - -If you would like to pass a `NULL` pointer to a binding, you can use `pointers.NULL` or pass `None`: - -```py -from pointers import time, NULL - -# these two do the same thing -print(time(NULL)) -print(time(None)) -``` - -## Custom Bindings - -You can create your own binding to a C function with `ctypes` and pointers.py. - -The recommended way to do it is via the `binds` function: - -```py -from pointers import binds -import ctypes - -dll = ctypes.CDLL("libc.so.6") # c standard library for linux - -# specifying the argtypes and restype isnt always required, but its recommended that you add it -dll.strlen.argtypes = (ctypes.c_char_p,) -dll.strlen.restype = ctypes.c_int - -@binds(dll.strlen) -def strlen(text: str): - ... -``` - -You can also use `binding`, but that isn't type safe: - -```py -from pointers import binding -import ctypes - -# ... - -strlen = binding(dll.strlen) # no type safety when calling strlen! -``` - -### Structs - -We need to set the `restype` when returning a struct, so first you need to define a `ctypes.Structure` object: - -```py -import ctypes - -dll = ctypes.CDLL("libc.so.6") - -class div_t(ctypes.Structure): - _fields_ = [ - ("quot", ctypes.c_int), - ("rem", ctypes.c_int), - ] - -dll.div.restype = div_t -``` - -Then, we need to create a pointers.py `Struct` that corresponds: - -```py -from pointers import Struct - -class DivT(Struct): - quot: int - rem: int -``` - -Then, we can finally define our binding: - -```py -from pointers import binds, Struct -import ctypes - -dll = ctypes.CDLL("libc.so.6") - -class div_t(ctypes.Structure): - _fields_ = [ - ("quot", ctypes.c_int), - ("rem", ctypes.c_int), - ] - -class DivT(Struct): - quot: int - rem: int - -dll.div.restype = div_t - -@binds(dll.div, struct=DivT) # this tells pointers.py that this struct will be returned -def div(numer: int, denom: int) -> DivT: - ... -``` - -## Why to use these bindings? - -The pointers.py bindings are nicer to use opposed to something like `ctypes`: - -_Comparison between `ctypes` and `pointers.py`_ - -```py -# ctypes - -import ctypes - -dll = ctypes.CDLL("libc.so.6") # this isn't cross platform, only works on linux -dll.strlen.argtypes = (ctypes.c_char_p,) -dll.strlen.restypes = ctypes.c_int - -print(dll.strlen(b"hello")) # not type safe and requires bytes object -``` - -```py -# pointers.py - -from pointers import strlen # this is cross platform - -print(strlen("hello")) # type safe and doesnt force you to use bytes -``` - -## Why not to use these bindings? - -Versatility and speed. The pointers.py bindings can make it harder to use your own functions with, as it forces you to use its pointer API. - -On top of that, the bindings are built on top of `ctypes`, which means that it cannot be faster. They also go through many type conversions in order to provide a nice API for the end user, which can slow things down significantly. diff --git a/docs/cpython_bindings.md b/docs/cpython_bindings.md deleted file mode 100644 index c579cbf..0000000 --- a/docs/cpython_bindings.md +++ /dev/null @@ -1,58 +0,0 @@ -# CPython ABI Bindings - -Pointers.py provides bindings out of the box for most of the CPython ABI. - -The ABI follows the naming convention of `Py<namespace>_<method>`, so you may use one by importing the namespace from pointers.py: - -```py -# example for PyEval_* methods -from pointers import PyEval - -PyEval.something(...) -``` - -However, the method names are in `PascalCase`, and according to [PEP 8](https://peps.python.org/pep-0008/), Python functions should be named in `snake_case`. - -Since pointers.py is PEP 8 compliant, method names have been converted to snake case. - -Here's an example with `PyEval_GetFrame`: - -```py -from pointers import PyEval - -frame = PyEval.get_frame() # calls PyEval_GetFrame -``` - -## Casting Pointers - -Some functions don't just return `PyObject`, and instead return something that can be casted instead (in this case, `PyFrameObject`): - -Any binding that doesn't return a `PyObject*` is simply converted to a `StructPointer`: - -```py -from pointers import PyEval - -frame = PyEval.get_frame() -# frame is not a frame object, instead its StructPointer[FrameObject] -``` - -You may cast this pointer to the correct Python object by calling `struct_cast`: - -```py -from pointers import PyEval, struct_cast - -frame = struct_cast(PyEval.get_frame()) -# frame is now a valid frame object! -``` - -## Limitations - -I did say above that there is support for _most_ of the ABI, so what isn't available right now? - -- Any function using a format string -- Any function defined in the header file without parameter names -- Anything using a macro (such as `_Py_NO_RETURN`) in its signature - -However, there are a few other functions that are unsupported due to arbitrary reasons. - -**These will all be supported in the future.** diff --git a/docs/getting_started.md b/docs/getting_started.md deleted file mode 100644 index 83b2646..0000000 --- a/docs/getting_started.md +++ /dev/null @@ -1,39 +0,0 @@ -# Getting Started - -## Installation - -To get started with pointers.py, install the library: - -### Linux/macOS - -```bash -$ python3 -m pip install -U pointers.py -``` - -### Windows - -```bash -$ py -3 -m pip install -U pointers.py -``` - -### From Source - -```bash -$ git clone https://github.com/ZeroIntensity/pointers.py && cd pointers.py -$ pip install . -``` - -**CPython 3.6+ is required** - -Now, to ensure everything is working properly we can run this simple program: - -```py -from pointers import to_ptr - -ptr = to_ptr("hello world") -print(*ptr) -``` - -**Note:** As of now, pointers.py does not officially support Python 3.11 and 3.12 - -Running this should print `hello world` into the console. diff --git a/docs/index.md b/docs/index.md deleted file mode 100644 index 12b02b7..0000000 --- a/docs/index.md +++ /dev/null @@ -1,53 +0,0 @@ -# Welcome to pointers.py`s documentation! - -## Bringing the hell of pointers to Python - -- [Source](https://github.com/ZeroIntensity/pointers.py) -- [PyPI](https://pypi.org/project/pointers.py) - -### Examples - -```py -from pointers import Pointer, decay - -a: str = '123' -b: str = 'abc' - -@decay -def move(ptr_a: Pointer[str], ptr_b: Pointer[str]): - ptr_a <<= ptr_b - -move(a, b) -print(a, b) # abc abc -``` - -```py -from pointers import _ - -ptr = _&"hello world" # creates a new pointer object -assert _*ptr == "hello world" -``` - -```py -from pointers import fopen, fprintf, fclose - -file = fopen("/dev/null", "w") # assigns to the c FILE* type -fprintf(file, "hello world") -fclose(file) -``` - -### Features - -- Fully type safe -- Pythonic pointer API -- Bindings for the entire C standard library and CPython ABI -- Segfaults - -### Why does this exist? - -The main purpose of pointers.py is to simply break the rules of Python, but has some other use cases: - -- Can help translate C/C++ code into Python -- Provides a nice learning environment for programmers learning how pointers work -- Makes it very easy to manipulate memory in Python -- Why _not_? diff --git a/docs/reference.md b/docs/reference.md deleted file mode 100644 index c49060a..0000000 --- a/docs/reference.md +++ /dev/null @@ -1,15 +0,0 @@ -# Reference - -<!-- prettier-ignore --> -::: pointers.util -::: pointers.base_pointers -::: pointers.c_pointer -::: pointers.decay -::: pointers.structure -::: pointers.std_structs -::: pointers.malloc -::: pointers.calloc -::: pointers.exceptions -::: pointers.magic -::: pointers._utils -::: pointers.var_pointer diff --git a/docs/using_pointers.md b/docs/using_pointers.md deleted file mode 100644 index df1d336..0000000 --- a/docs/using_pointers.md +++ /dev/null @@ -1,271 +0,0 @@ -# Using Pointers - -## Creation - -To create a pointer, you can use `to_ptr`, like so: - -```py -from pointers import to_ptr - -ptr = to_ptr("hello world") -``` - -You can also use the `_` object to replicate the address-of operator, like in other languages: - -```py -from pointers import _ - -ptr = _&"hello world" -``` - -Finally, you can directly call `Pointer.make_from`: - -```py -from pointers import Pointer - -ptr = Pointer.make_from("hello world") -``` - -**Note:** `Pointer.make_from` is more a low level function for creating a pointer. Its API may be changed at any time without warning. - -## Dereferencing - -There are a few ways to get the underlying value of the pointer, the simplest being calling the `dereference()` method, like so: - -```py -from pointers import _ - -ptr = _&"hi" -print(ptr.dereference()) # prints out "hi" -``` - -Unfortunately, `dereference` is a pretty long name and doesn't look very pretty when you call it everywhere. Fortunately though, there are different (and more preffered) ways of dereferencing the pointer. - -We can use the `_` object to once again replicate the syntax from other languages: - -```py -from pointers import _ - -ptr = _&"hi" -print(_*ptr) -``` - -In some cases like this one, you can even just directly use `*`, without even having to touch `_`! - -```py -ptr = _&"hi" -print(*ptr) # works just fine -``` - -However, `*` is for arg splats, which introduces some problems. You can use `~` as an alternative, which will always work: - -```py -ptr = _&"hi" -print(~ptr) -# ~ is a unary operator, so we can use it anywhere we want -``` - -## Decaying - -Converting objects to pointers everywhere may be a bit ugly. To fix this, pointers.py provides a few functions to decay parameters into their pointer equivalents. - -The most simple one is `decay`: - -```py -from pointers import decay, Pointer - -@decay -def my_function(a: str, b: str, c: Pointer): # must be type hinted as Pointer to convert - print(a, b, *c) - -my_function('a', 'b', 'c') -``` - -This will be fine for most people, but it removes type safety on the target function. If you don't care about type safety in your code, then don't worry about this, but if you do, then there are alternatives. - -The first alternative is `decay_annotated`, which decays parameters hinted as `Annotated[T, Pointer]` to a pointer. - -Here's an example: - -```py -from pointers import decay_annotated, Pointer -from typing import Annotated # if you are below python 3.9, you can use typing_extensions here - -@decay_annotated -def my_function(a: str, b: str, c: Annotated[str, Pointer]): - print(a, b, *c) - -my_function('a', 'b', 'c') -``` - -However, `decay_annotated` has a very large drawback. - -While it adds type safety for calling the function, it breaks it inside. A type checker still thinks that the argument is a `str`, and not a `Pointer`. - -Take the following as an example: - -```py -@decay_annotated -def my_function(a: str, b: str, c: Annotated[str, Pointer]): - print(a, b, ~c) # type checker error! -``` - -The solution is to use `decay_wrapped`, which takes a fake function as a parameter: - -```py -from pointers import decay_wrapped, Pointer - -def my_function_wrapper(a: str, b: str, c: str) -> None: # this should mimick your actual function - ... - -@decay_wrapped(my_function_wrapper) -def my_function(a: str, b: str, c: Pointer[str]): - print(a, b, *c) - print(a, b, ~c) # no type checker error, it thinks c is a pointer! - -my_function('a', 'b', 'c') # works just fine, type checker things c takes a string -``` - -If the wrapper doesn't match, things won't work properly: - -```py -from pointers import decay_wrapped, Pointer - -def my_function_wrapper(a: str, b: str, c: str, d: str) -> None: - ... - -@decay_wrapped(my_function_wrapper) -def my_function(a: str, b: str, c: Pointer[str]): - print(a, b, *c) - -my_function('a', 'b', 'c') # type checker error! missing parameter "d" -``` - -## Assignment - -We can change where the pointer is looking at by using `assign`, or more commonly, the `>>=` operator: - -```py -from pointers import _ - -ptr = _&"hi" -ptr.assign("hello") -ptr >>= "hello" # equivalent to the above - -print(*ptr) # prints out "hello" -``` - -However, this **does not** change the original value. To do that, see the section below. - -## Movement - -Movement is somewhat complicated. In low level languages with pointers, you can use dereferencing assignment, like so: - -```c -int b = 1; -int* a = &b; -*a = 2; -``` - -Unfortunately, this isn't really possible in Python. Instead, pointers.py has a feature called data movement. You can use it with `Pointer.move` or the more preffered `<<=` operator: - -```py -from pointers import _ - -text: str = "hello world" -ptr = _&text -ptr <<= "world hello" -print(text) # prints out "world hello" -``` - -**This is extremely dangerous.** - -We didn't overwrite the variable `text` with `"world hello"`, we overwrote the string itself. We can run the following to then demonstrate: - -```py -# ^^ insert the code from above -print("hello world") # prints out "world hello", since we overwrote it -``` - -While pointers.py does its best to try and prevent segmentation faults, data movement can cause several problems, mainly with garbage collection and reference counting. If you don't know what those are, I highly recommend staying away from data movement. - -In fact, unless you are familiar with the CPython internal machinery, I wouldn't touch movement at all. - -### For C/C++ developers - -Data movement would be like the following C code: - -```c -int* ptr = &1; // lets pretend this is allowed (which it is in python) -*ptr = 2; -assert(1 == 2); -``` - -### Bypassing size limits - -An important safety feature of movement is making sure that you can't move an object larger than the underlying value. - -This is important for several reasons, but if you truly need to bypass it you can use the `^=` operator, or pass `unsafe=True` to `move`: - -```py -from pointers import _ - -ptr = _&"123" -ptr ^= "1234" # this is the same as ptr.move("1234", unsafe=True) -``` - -Doing this is strictly experimental. - -Moving objects too large also makes your code vulnerable to [buffer overflow attacks](https://en.wikipedia.org/wiki/Buffer_overflow), along with a chance of segmentation faults. - -## Null Pointers - -If you would like to point to nothing, you can use `NULL`. - -Note that you cannot dereference a `NULL` pointer: - -```py -from pointers import NULL, to_ptr - -ptr = to_ptr(NULL) -~ptr # NullPointerError -``` - -You can also assign an existing pointer to `NULL`: - -```py -from pointers import NULL, to_ptr - -ptr = to_ptr(1) -~ptr # works just fine -ptr >>= NULL -~ptr # NullPointerError -``` - -## Handling Segmentation Faults - -If you've ever used a language like C or C++, you probably know what a segmentation fault/segfault is. - -These can happen when a memory error occurs (e.g. accessing a NULL pointer), and can be annoying to debug in Python. - -Luckily, pointers.py has a custom built handler for converting segfaults into Python exceptions. - -Here's an example: - -```py -from pointers import handle -import ctypes - -@handle -def main(): - ctypes.string_at(0) # 0 is the same as a NULL address - -main() -# instead of python crashing with a segfault, pointers.SegmentViolation error occurs -``` - -### Pointer Methods - -Most pointer methods where a segment violation could occur (`dereference`, `move`, etc.) are decorated with `handle`, so you don't have to worry about manually catching those yourself. - -However, methods like `move` can be destructive and cause the error outside of the function (such as when Python does garbage collection), so you may need to make a `main` method and decorate it with `handle` to catch it. diff --git a/docs/variable_pointers.md b/docs/variable_pointers.md deleted file mode 100644 index 89cdd2a..0000000 --- a/docs/variable_pointers.md +++ /dev/null @@ -1,77 +0,0 @@ -# Variable Pointers - -## What's the difference? - -An object pointer (created by `to_ptr` or `Pointer.make_from`) points to the actual Python object (`PyObject*`), while a variable pointer points to that actual variable. - -```py -hello = "123" -ptr = to_ptr(hello) -# ptr now points to "123", not "hello" -``` - -## Creation - -You can make a variable pointer through `to_var_ptr`: - -```py -from pointers import to_var_ptr - -a = "hi" -ptr = to_var_ptr(a) -``` - -Note that of course you can't use a literal, because that isn't a variable: - -```py -from pointers import to_var_ptr - -ptr = to_var_ptr(123) # ValueError -``` - -## Movement - -Moving is much different when it comes to variable pointers. With an object pointer, you are overwriting that actual value, while with variable pointers you are just changing the value of that variable. - -You can use movement the same way you would with an object pointer: - -```py -from pointers import to_var_ptr - -my_var = 1 -my_ptr = to_var_ptr(my_var) -my_ptr <<= 2 -print(my_var, 1) -# outputs 2 1, since we didnt overwrite 1 like we would with object pointers -``` - -You are free to use movement however you like with variable pointers. It isn't dangerous, unlike its counterpart. - -### For C/C++ developers - -Movement in variable pointers is equivalent to the following C code: - -```c -int my_var = 1; // "my_var = 1" -int my_ptr = &my_var; // "my_ptr = to_var_ptr(my_var)" -*my_ptr = 2; // "my_ptr <<= 2" -// my_var is now 2 (the actual 1 is unchanged, thankfully) -``` - -## Assignment - -Assignment works the same way as it does with object pointers: - -```py -from pointers import to_var_ptr, NULL - -hello = "world" -foo = "bar" - -ptr = to_var_ptr(hello) -print(*ptr) # world -ptr >>= NULL -# ... -ptr >>= foo -print(*ptr) # bar -``` diff --git a/docs/working_by_example.md b/docs/working_by_example.md deleted file mode 100644 index 2b0fa57..0000000 --- a/docs/working_by_example.md +++ /dev/null @@ -1,91 +0,0 @@ -# Working By Example - -Now that we've learned how to use pointers.py, lets build some small scripts to try out some of its features. - -## Making one equal two - -**Note:** This may not work depending on your build of CPython. - -Lets start out with creating a pointer to `1`, and then moving `2` to it: - -```py -from pointers import _ - -ptr = _&1 -ptr <<= 2 - -assert 1 == 2 -``` - -Running this will work just fine, and no `AssertionError` will be raised. - -But how do we revert our changes now? `1` has been overwritten, so we can't just move a `1` back into the pointer. - -If you want, you can take a second to think about how to do it. - ---- - -We can cache our `1` by using memory allocation. Since the `1` will be copied to its own memory space, it won't get affected by overwriting `1`. - -You can try this out yourself. - -```py -from pointers import malloc, _ - -one = malloc(28) -one <<= 1 - -ptr = _&1 -ptr <<= 2 - -print(1, ~one) -``` - -Running this will output `2 1`! - -Ok, lets allocate a `1` before we overwrite it: - -```py -from pointers import malloc, free, _ - -cache = malloc(28) -cache <<= 1 - -ptr = _&1 -``` - -Then, lets move the allocated `1` back into our pointer at the end of the program: - -```py -ptr = _&1 -ptr <<= 2 - -assert 1 == 2 - -ptr <<= ~cache -assert 1 != 2 -``` - -Don't forget to free the memory as well: - -```py -free(cache) -``` - -Here's the final result: - -```py -from pointers import malloc, free, _ - -cache = malloc(28) -cache <<= 1 - -ptr = _&1 -ptr <<= 2 - -assert 1 == 2 - -ptr <<= ~cache -assert 1 != 2 -free(cache) -``` diff --git a/examples/binding_example.py b/examples/binding_example.py deleted file mode 100644 index 7be440e..0000000 --- a/examples/binding_example.py +++ /dev/null @@ -1,5 +0,0 @@ -from pointers import fclose, fopen, fprintf - -file = fopen("/dev/null", "w") -fprintf(file, "hello world") -fclose(file) diff --git a/examples/calloc_example.py b/examples/calloc_example.py deleted file mode 100644 index a6f9128..0000000 --- a/examples/calloc_example.py +++ /dev/null @@ -1,10 +0,0 @@ -from pointers import calloc, free - -array = calloc(10, 28) - -for index, ptr in enumerate(array): - ptr <<= index + 1 - -py_array = [~i for i in array] -print(py_array) -free(array) diff --git a/examples/custom_binding_example.py b/examples/custom_binding_example.py deleted file mode 100644 index b43de35..0000000 --- a/examples/custom_binding_example.py +++ /dev/null @@ -1,57 +0,0 @@ -import ctypes - -from pointers import Struct, StructPointer, binds - -dll = ctypes.CDLL("libc.so.6") - - -class Lconv(Struct): - decimal_point: str - thousands_sep: str - grouping: str - int_curr_symbol: str - currency_symbol: str - mon_decimal_point: str - mon_thousands_sep: str - mon_grouping: str - positive_sign: str - negative_sign: str - frac_digits: str - p_cs_precedes: str - p_sep_by_space: str - n_sep_by_space: str - p_sign_posn: str - n_sign_posn: str - - -class lconv(ctypes.Structure): - _fields_ = [ - ("decimal_point", ctypes.c_char_p), - ("thousands_sep", ctypes.c_char_p), - ("grouping", ctypes.c_char_p), - ("int_curr_symbol", ctypes.c_char_p), - ("currency_symbol", ctypes.c_char_p), - ("mon_decimal_point", ctypes.c_char_p), - ("mon_thousands_sep", ctypes.c_char_p), - ("mon_grouping", ctypes.c_char_p), - ("positive_sign", ctypes.c_char_p), - ("negative_sign", ctypes.c_char_p), - ("int_frac_digits", ctypes.c_char), - ("frac_digits", ctypes.c_char), - ("p_cs_precedes", ctypes.c_char), - ("p_sep_by_space", ctypes.c_char), - ("n_sep_by_space", ctypes.c_char), - ("p_sign_posn", ctypes.c_char), - ("n_sign_posn", ctypes.c_char), - ] - - -dll.localeconv.restype = ctypes.POINTER(lconv) - - -@binds(dll.localeconv, struct=Lconv) -def localeconv() -> StructPointer[Lconv]: - ... - - -print((~localeconv()).decimal_point) diff --git a/examples/malloc_example.py b/examples/malloc_example.py deleted file mode 100644 index fdc7f29..0000000 --- a/examples/malloc_example.py +++ /dev/null @@ -1,7 +0,0 @@ -from pointers import free, malloc - -memory = malloc(52) -memory <<= "abc" -print(*memory) # abc -free(memory) -print(*memory) # FreedMemoryError diff --git a/examples/move_example.py b/examples/move_example.py deleted file mode 100644 index ff2d71a..0000000 --- a/examples/move_example.py +++ /dev/null @@ -1,13 +0,0 @@ -from pointers import Pointer, decay - -a: str = "123" -b: str = "abc" - - -@decay -def move(ptr_a: Pointer[str], ptr_b: Pointer[str]): - ptr_a <<= ptr_b - - -move(a, b) -print(a, b) # abc abc diff --git a/examples/struct_example.py b/examples/struct_example.py deleted file mode 100644 index a356a34..0000000 --- a/examples/struct_example.py +++ /dev/null @@ -1,13 +0,0 @@ -from pointers import Struct - - -class MyStruct(Struct): - a: str - b: str - - -a = MyStruct() -a.a = "a" -a.b = "b" - -print(a, a.a, a.b) diff --git a/gen.py b/gen.py deleted file mode 100644 index 935c819..0000000 --- a/gen.py +++ /dev/null @@ -1,495 +0,0 @@ -# this file shouldnt be pep 8 checked -from __future__ import annotations - -import asyncio -import ctypes -import os -import re -import sysconfig -from contextlib import suppress - -import aiofiles # type: ignore -import aiohttp -import requests -from bs4 import BeautifulSoup, Tag - -from src.pointers.std_structs import STRUCT_MAP - -PAGES: dict[str, BeautifulSoup] = {} -BASE_URL: str = "https://docs.python.org/3.11/c-api" -C_FUNC = re.compile( - r"^(((.+) )?(\w+(\**)*)) (\w+)\(((((.+ \w+(\[\])?,?)*(, ?\.\.\.)?))|void)\)+$" -) -COMMENT = re.compile(r"\/\*.*\*\/") - - -def ct(data: str) -> str: - return f"ctypes.{data}" - - -def ctc(data: str) -> str: - return f"ctypes.c_{data}" - - -def ctp(data: str) -> str: - return f"ctypes.POINTER({data})" - - -WCHAR_P = ctc("wchar_p") -CHAR_P = ctc("char_p") -VOID_P = ctc("void_p") -WCHAR = ctc("wchar") -DOUBLE_QUOTE: str = '"' -TRIPLE_QUOTE: str = '"""' -SSIZE = ctc("ssize_t") -INT = ctc("int") - -C_TYPES = { - "void": "None", - "PyObject*": ct("py_object"), - "int": INT, - "void*": VOID_P, - "Py_ssize_t": SSIZE, - "char": ctc("char"), - "char*": CHAR_P, - "const char*": CHAR_P, - "unsigned long": ctc("ulong"), - "unsigned long long": ctc("ulonglong"), - "unsigned int": ctc("uint"), - "long long": ctc("longlong"), - "size_t": ctc("size_t"), - "double": ctc("double"), - "long": ctc("long"), - "uint64_t": ctc("uint64"), - "int64_t": ctc("int64"), - # docs have invalid definitions of wchar apparently - "wchar*": WCHAR_P, - "wchar_t*": WCHAR_P, - "w_char*": WCHAR_P, - "va_list": VOID_P, - "wchar_t": WCHAR, - "PyTypeObject": "PyTypeObject", - "Py_UCS4": "Py_UCS4", - "PyThreadState": "PyThreadState", - "PyVarObject": "PyVarObject", - "PyFrameObject": "PyFrameObject", - "PyInterpreterState": "PyInterpreterState", - "PyType_Spec": "PyType_Spec", - "Py_tss_t": "Py_tss_t", - "Py_hash_t": SSIZE, - "Py_buffer": "Py_buffer", - "PyOS_sighandler_t": VOID_P, - "PyGILState_STATE": INT, - "PyModuleDef": "PyModuleDef", - "struct PyModuleDef": "PyModuleDef", - "PyCodeObject": "PyCodeObject", - "PyCapsule_Destructor": VOID_P, - "PyGILState": INT, - "PyMethodDef": "PyMethodDef", - "PyGetSetDef": "PyGetSetDef", - "struct PyMethodDef*": "ctypes.POINTER(PyMethodDef)", - "struct PyGetSetDef*": "ctypes.POINTER(PyGetSetDef)", - "FILE*": VOID_P, - "PySendResult": INT -} - -CT_TYPES = { - "char_p": "StringLike", - "wchar_p": "str", - "wchar": "str", - "long": "int", - "longlong": "int", - "size_t": "int", - "ssize_t": "int", - "int": "int", - "uint64": "int", - "int64": "int", - "uint": "int", - "ulong": "int", - "ulonglong": "int", - "py_object": "PyObjectLike", - "void_p": "PointerLike", - "char": "CharLike", - "double": "int", -} - -NEWLINE = "\n" - -HARDCODED_NAMES: dict[str, str] = { - "GC_IsTracked": "gc_is_tracked", - "GC_Track": "gc_track", - "GC_UnTrack": "gc_untrack", - "GC_IsFinalized": "gc_is_finalized", - "GC_Del": "gc_del", -} - -NAME_GROUPS: list[str] = ["ASCII", "UTF", "UCS", "FS"] - - -def not_found(item: str, func: str) -> None: - print("Not found...", item, "in", func) - - -def _write_autogen(file: str, text: str) -> None: - with open(f"./src/pointers/{file}") as f: - lines = f.read().split("\n") # readlines was keeping the \n - - with open(f"./src/pointers/{file}", "w") as f: - try: - index = lines.index("# autogenerated") - except ValueError: - index = lines.index( - "# autogenerated " - ) # in case there's trailing whitespace - - f.write( - "\n".join(lines[: index + 1]) + f"\n{text}", - ) - - -def _get_type(ctype: str, *, add_pointer: bool = False) -> str | None: - typ = C_TYPES.get(ctype) - - if typ: - return f"{typ if not add_pointer else f'ctypes.POINTER({typ})'}" - else: - if ctype.endswith("*"): - index = ctype.index("*") - ptrs = ctype[index:].count("*") + add_pointer - join = ctype[:index] - - typ = C_TYPES.get(f"{join}*") - - if not typ: - typ = C_TYPES.get(join) - else: - ptrs -= 1 - - if not typ: - return None - - typ = "".join( - [ - *["ctypes.POINTER(" for _ in range(ptrs)], - typ, - *[")" for _ in range(ptrs)], - ] - ) - return typ - return None - - -async def _gen_str( - name: str | None, - signature: str, - params: dict[str, list[str]], - minver: str | None, -) -> str | None: - signature = signature.replace(" *", "* ").replace("* *", "** ").replace("struct ", "") - - for i in {"#", "//", "typedef", "static", "/*"}: - if signature.startswith(i): - return None - match = C_FUNC.match(signature) - - if not name: - if match: - name = match.group(6) - - if match and (name not in params): - assert name - params[name] = [] - group = match.group(1) - ret = _get_type(group) - - if not ret: - not_found(group, name) - return None - - if match.group(12): - argtypes = "" - else: - args = match.group(7) - if not args: - args = "void" - argtypes = ", (" - - if args != "void": - for arg in args.split(", "): - arg_split = arg.split(" ") - argname = arg_split.pop(-1) - add_pointer: bool = False - - if argname.endswith("[]"): - argname = argname[:-2] - add_pointer = True - - params[name].append(argname if argname != "def" else "df") - - join = " ".join(arg_split).replace( - "const ", "" - ) # we dont care about consts - typ = _get_type(join, add_pointer=add_pointer) - - if not typ: - not_found(join, name) - continue - - argtypes += typ + "," - - argtypes += ")" - - return f"# {signature}\n_register('{name}', {ret}{argtypes}{f', minver={DOUBLE_QUOTE}{minver}{DOUBLE_QUOTE},' if minver else ''})\n" - return None # to make mypy happy - - -async def _gen_ct_bindings() -> dict[str, list[str]]: - params: dict[str, list[str]] = {} - - out: str = "\n\n" - async with aiohttp.ClientSession() as s: - async with s.get(f"{BASE_URL}/stable.html#stable-application-binary-interface") as resp: - soup = BeautifulSoup(await resp.text(), features="html.parser") - ul = soup.find("ul", attrs={"class": "simple"}) - assert ul - - for tag in ul: - if not isinstance(tag, Tag): - continue - - p = tag.find("p", recursive=True) - assert p - a = p.find("a") - - if a: - assert type(a) is Tag - name: str = a.get_text().replace("()", "") - href = a.attrs["href"] - path = href[: href.find(".html")] - - if path not in PAGES: - print("Loading page... ", path) - PAGES[path] = BeautifulSoup( - requests.get(f"{BASE_URL}/{path}.html").text, - features="html.parser", - ) - - page = PAGES[path] - signature: str = "" - doc = page.find(id=f"c.{name}") - assert doc, f"{page} {name}" - - for tg in doc: - if isinstance(tg, str): - signature += tg if tg != "\n" else "" - continue - - text: str = tg.get_text() - if text != "¶": - signature += text - - assert type(doc) is Tag - parent = doc.parent - assert parent - - minver_soup = parent.find( - "span", - attrs={"class": "versionmodified added"}, - recursive=True, - ) - minver: str | None = None - - if minver_soup: - minver = minver_soup.get_text()[:-1].split(" ")[-1] - # this is super janky - - result = await _gen_str( - name, - signature, - params, - minver, - ) - - if result: - out += result - - include = sysconfig.get_path("include") - - print(f"Reading signatures from {include}") - for root, _, files in os.walk(include): - for i in files: - path = os.path.join(root, i) - if os.path.isdir(path): - continue - - async with aiofiles.open(path) as f: - print("Loading file... ", path) - - lines = COMMENT.sub("", (await f.read()).replace("\n", "").replace(" ", "").replace(" ", "")).split(";") - - for raw_line in lines: - if "PyAPI_FUNC" not in raw_line: - continue - - split = raw_line.split("PyAPI_FUNC") - line = 'PyAPI_FUNC' + ''.join(split[1:]) - line = line.replace(";", "") - - idx = line.index(")") - line = line[11:idx] + line[idx + 1:] - - patched_line = "" - - for index, char in enumerate(line): - patched_line += char - - if char == ",": - with suppress(IndexError): - if line[index + 1] != " ": - patched_line += " " - - - patched_line = patched_line.replace(" *", "* ").replace("* *", "** ").replace(" ", " ").replace(" )", ")").replace(" ,", ",") - result = await _gen_str( - None, - patched_line, - params, - None, - ) - - if result: - out += result - else: - print("No result...", patched_line) - - _write_autogen("_pyapi.py", out) - return params - - -def map_type(typ: type["ctypes._CData"] | None) -> str: - if not typ: - return "None" - name = typ.__name__ - - if name.startswith("LP_"): - actual_name = name[3:] - - for k, v in STRUCT_MAP.items(): - s_name: str = k.__name__ - if s_name == actual_name: - return f"StructPointer[{v.__name__}]" - - return "PointerLike" - - return CT_TYPES[name[2:] if name != "py_object" else name] - - -def get_converter(data: str, typ: str) -> str: - if typ == "StringLike": - return f"make_string({data})" - - elif typ == "CharLike": - return f"make_char({data})" - - elif typ == "Format": - return f"make_format({data})" - - elif typ == "PyObjectLike": - return f"_deref_maybe({data})" - - return data - - -async def main(): - params = await _gen_ct_bindings() - while True: - yn = input("regen api_bindings.py (y/n)? ").lower() - - if yn not in {"y", "n"}: - continue - - if yn == "n": - return - break - - out: str = "" - from src.pointers._pyapi import API_FUNCS - - funcs: dict[str, list[str]] = {} - - for k, v in API_FUNCS.items(): - func = v[0] - - if not func: - continue - - zip_params = (params[k], func.argtypes) - - if func.argtypes is None: - print("No argtypes...", func.__name__) - continue - - fparams = [f"{param}: {map_type(typ)}" for param, typ in zip(*zip_params)] - restype: type["ctypes._CData"] = func.restype # type: ignore - - name_split = k.split("_") - section = name_split[0] - - if not section: - name_split.pop(0) - section = "_" + name_split[0] - - if section not in funcs: - funcs[section] = [] - - origin_name = "_".join(name_split[1:]) - name = HARDCODED_NAMES.get(origin_name) or "" - - if not name: - for i in NAME_GROUPS: - if i in origin_name: - index = origin_name.index(i) - origin_name = origin_name.replace( - i, - f"{'_' if index else ''}{i.lower()}{'_' if (index + len(i)) != len(origin_name) else ''}", - ) - - for index, i in enumerate(origin_name): - lower: str = i.lower() - - if i.isupper(): - name += ("_" if index else "") + lower - else: - name += lower - - if name in {"or", "and", "import", "not", "is"}: - name += "_" - - funcs[section].append( - f""" - # {k} - @staticmethod - def {name}({', '.join(fparams)}) -> {map_type(restype)}: - return api_binding_base(API_FUNCS["{k}"], {', '.join([get_converter(i, map_type(typ)) for i, typ in zip(*zip_params)])}) -""" - ) - - for k, v in funcs.items(): - out += f"""class {k}(_CallBase): - {TRIPLE_QUOTE}Namespace containing API functions prefixed with `{k}_`{TRIPLE_QUOTE} -{NEWLINE.join(v)} -""" - - all_str = "__all__ = (" - - for i in funcs: - all_str += f'"{i}",' - - out = all_str + ")\n\n" + out - - _write_autogen("api_bindings.py", out) - print("success!") - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/hatch.toml b/hatch.toml new file mode 100644 index 0000000..1ad608e --- /dev/null +++ b/hatch.toml @@ -0,0 +1,13 @@ +[targets.sdist] +only-include = ["src/pointers"] + +[build.targets.wheel] +packages = ["src/pointers"] + +[build.targets.wheel.hooks.scikit-build] +experimental = true + +[build.targets.wheel.hooks.scikit-build.cmake] +source-dir = "." +build-type = "Debug" +verbose = true diff --git a/hatch_build.py b/hatch_build.py deleted file mode 100644 index c3816d8..0000000 --- a/hatch_build.py +++ /dev/null @@ -1,104 +0,0 @@ -import os -import shutil -import sysconfig -from contextlib import suppress -from distutils.extension import Extension -from glob import glob -from pathlib import Path - -from find_libpython import find_libpython -from hatchling.builders.hooks.plugin.interface import BuildHookInterface -from hatchling.plugin import hookimpl -from setuptools._distutils.ccompiler import new_compiler - -ext_modules = [ - Extension( - "_pointers", - include_dirs=["<header-file-directory>"], - sources=glob("src/_pointers/*"), - ), -] - - -class CustomBuildHook(BuildHookInterface): - PLUGIN_NAME = "custom" - - def initialize(self, version: str, data: dict): - self.clean() - compiler = new_compiler() - ext = os.path.join(self.root, "ext") - lib = os.path.join(ext, "./ext/lib") - - # logic taken from distutils - if sysconfig.get_config_var('Py_ENABLE_SHARED'): - if not sysconfig.is_python_build(): - compiler.add_library_dir(sysconfig.get_config_var('LIBDIR')) - else: - compiler.add_library_dir('.') - - libpython_path = find_libpython() - if not libpython_path: - self.app.display_warning("failed to find libpython") - - compiler.add_library_dir(str(Path(libpython_path).parent.absolute())) - - compiler.add_include_dir( - os.path.join(sysconfig.get_path("platstdlib"), "lib") - ) - - compiler.add_include_dir(sysconfig.get_path("include")) - compiler.define_macro("PY_SSIZE_T_CLEAN") - - self.app.display_waiting("compiling _pointers") - - try: - compiler.compile( - glob("./src/mod.c"), - output_dir=ext, - extra_preargs=["-fPIC", "-v"] if os.name != "nt" else [], - ) - except Exception: - self.app.abort("failed to compile _pointers") - - self.app.display_success("successfully compiled _pointers") - self.app.display_waiting("linking _pointers") - - files = [] - - for root, _, fls in os.walk(ext): - for i in fls: - if i.endswith(".o"): - files.append(os.path.join(root, i)) - - try: - compiler.link_shared_lib( - files, - "_pointers", - output_dir=lib, - debug=True - ) - except Exception: - self.app.abort("failed to link _pointers") - - self.app.display_success("successfully linked _pointers") - - with suppress(KeyError): - data["force_include"][ - os.path.join(lib, "lib_pointers.so") - ] = "src/_pointers.so" - - with suppress(KeyError): - data["infer_tag"] = True - - with suppress(KeyError): - data["pure_python"] = False - - def clean(self, *_): - path = os.path.join(self.root, "ext") - if os.path.exists(path): - shutil.rmtree(path) - - -@hookimpl -def hatch_register_build_hook(): - return CustomBuildHook diff --git a/pyproject.toml b/pyproject.toml index fd6a90c..a299c2a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [build-system] -requires = ["setuptools", "toml"] -build-backend = "setuptools.build_meta" +requires = ["hatchling", "scikit-build-core"] +build-backend = "hatchling.build" [project] name = "pointers.py" @@ -21,19 +21,13 @@ classifiers = [ ] dependencies = [ "typing_extensions", - "varname" ] -version = "3.0.1" +version = "4.0.0" [project.urls] Documentation = "https://pointers.zintensity.dev" Issues = "https://github.com/ZeroIntensity/pointers.py/issues" Source = "https://github.com/ZeroIntensity/pointers.py" -[tool.ward] -path = ["tests"] -capture-output = true -order = "standard" -test-output-style = "test-per-line" -fail-limit = 5 -progress-style = ["bar"] +[tool.scikit-build.install] +strip = false diff --git a/requirements_dev.txt b/requirements_dev.txt deleted file mode 100644 index d29b613..0000000 --- a/requirements_dev.txt +++ /dev/null @@ -1,4 +0,0 @@ -flake8~=4.0.1 -isort~=5.10.1 -pre-commit~=2.17.0 -mypy~=0.971 diff --git a/setup.py b/setup.py deleted file mode 100644 index 1e90519..0000000 --- a/setup.py +++ /dev/null @@ -1,23 +0,0 @@ -import toml -from setuptools import Extension, setup - -with open("./README.md") as f: - long_desc: str = f.read() - -if __name__ == "__main__": - with open("./pyproject.toml", "r") as f: - data = toml.load(f) - setup( - name="pointers.py", - version="3.0.1", - packages=["pointers"], - project_urls=data["project"]["urls"], - package_dir={"": "src"}, - license="MIT", - ext_modules=[ - Extension( - "_pointers", - ["./src/mod.c"] - ) - ], - ) diff --git a/src/_pointers.pyi b/src/_pointers.pyi deleted file mode 100644 index 6ef02c9..0000000 --- a/src/_pointers.pyi +++ /dev/null @@ -1,19 +0,0 @@ -from types import FrameType -from typing import Any, Callable, Type, TypeVar - -_T = TypeVar("_T") -_A = TypeVar("_A") - -def add_ref(__obj: Any) -> None: ... -def remove_ref(__obj: Any) -> None: ... -def force_set_attr(__typ: type[Any], __key: str, __value: Any) -> None: ... -def set_ref(__obj: Any, __count: int) -> None: ... -def handle( - __func: Callable[..., _T], - __args: tuple[Any, ...] | None = None, - __kwargs: dict[str, Any] | None = None, -) -> _T: ... -def run_stack_callback( - __size: int, __ptr: Type[_T], __func: Callable[[_T], _A] -) -> _A: ... -def force_update_locals(__f: FrameType, __key: str, __value: Any) -> None: ... diff --git a/src/_pointers/mod.c b/src/_pointers/mod.c new file mode 100644 index 0000000..8a3073e --- /dev/null +++ b/src/_pointers/mod.c @@ -0,0 +1,83 @@ +#define Py_BUILD_CORE +#include <Python.h> +#include "internal/pycore_object.h" +#define METHOD(name, flags) {#name, name, flags, NULL} + +static PyObject * +incref(PyObject *self, PyObject *ob) +{ + Py_INCREF(ob); + Py_RETURN_NONE; +} + + +static PyObject * +decref(PyObject *self, PyObject *ob) +{ + Py_DECREF(ob); + Py_RETURN_NONE; +} + +static PyObject * +setref(PyObject *self, PyObject *args) +{ + PyObject *ob; + Py_ssize_t refcount; + + if (!PyArg_ParseTuple(args, "On", &ob, &refcount)) + return NULL; + + Py_SET_REFCNT(ob, refcount); + Py_RETURN_NONE; +} + +static PyObject * +deref(PyObject *self, PyObject *addr) +{ + if (!PyLong_Check(addr)) + { + PyErr_SetString(PyExc_TypeError, "expected integer as address"); + return NULL; + } + + void *ptr = PyLong_AsVoidPtr(addr); + PyObject *obj = (PyObject *) ptr; + Py_INCREF(obj); + return obj; +} + +static PyObject * +getref(PyObject *self, PyObject *ob) +{ + return PyLong_FromSsize_t(Py_REFCNT(ob)); +} + +static PyObject * +setimmortal(PyObject *self, PyObject *ob) +{ + #if Py_MINOR_VERSION >= 12 + _Py_SetImmortal(ob); + #endif + Py_RETURN_NONE; +} + +static PyMethodDef _pointers_methods[] = { + METHOD(incref, METH_O), + METHOD(decref, METH_O), + METHOD(setref, METH_VARARGS), + METHOD(deref, METH_O), + METHOD(getref, METH_O), + METHOD(setimmortal, METH_O), + {NULL, NULL, 0, NULL} +}; + +static PyModuleDef _pointers_module = { + .m_name = "_pointers", + .m_methods = _pointers_methods +}; + +PyMODINIT_FUNC +PyInit__pointers() +{ + return PyModuleDef_Init(&_pointers_module); +} diff --git a/src/mod.c b/src/mod.c deleted file mode 100644 index 46b5918..0000000 --- a/src/mod.c +++ /dev/null @@ -1,296 +0,0 @@ -#include <Python.h> - -#if PY_MINOR_VERSION < 10 -static inline PyObject* Py_NewRef(PyObject* ob) { - Py_INCREF(ob); - return ob; -} -#endif - -#if PY_MAJOR_VERSION != 3 -#error "Python 3 is needed to build" -#endif -#if PY_MINOR_VERSION >= 11 -#define GET_CODE(frame) PyFrame_GetCode(frame); -#define GET_LOCALS(frame) PyFrame_GetLocals(frame); -#else -#define GET_CODE(frame) Py_NewRef(frame->f_code); -#define GET_LOCALS(frame) Py_NewRef(frame->f_locals); -#endif -#include <signal.h> -#include <setjmp.h> -#include <stdbool.h> -#include <stdio.h> -#include <frameobject.h> -#define GETOBJ() \ - PyObject* obj; if (!PyArg_ParseTuple(args, "O", &obj)) return NULL - -#ifdef _WIN32 -#include <malloc.h> -#endif - -#if defined(__GNUC__) -#define ALLOCA(size) alloca(size) -#elif defined(_WIN32) -#define ALLOCA(size) _alloca(size) -#else -#define ALLOCA( \ - size) \ - NULL; PyErr_SetString(PyExc_RuntimeError, "stack allocations are not supported on this system!"); return NULL; -#endif - -static jmp_buf buf; - -static PyObject* add_ref(PyObject* self, PyObject* args) { - GETOBJ(); - Py_INCREF(obj); - Py_RETURN_NONE; -} - -static PyObject* remove_ref(PyObject* self, PyObject* args) { - GETOBJ(); - Py_DECREF(obj); - Py_RETURN_NONE; -} - -static PyObject* set_ref(PyObject* self, PyObject* args) { - PyObject* obj; - Py_ssize_t count; - if (!PyArg_ParseTuple( - args, - "On", - &obj, - &count - )) return NULL; - obj->ob_refcnt = count; // i dont care - Py_RETURN_NONE; -} - -static PyObject* force_set_attr(PyObject* self, PyObject* args) { - PyTypeObject* type; - PyObject* value; - char* key; - - if (!PyArg_ParseTuple( - args, - "OsO", - &type, - &key, - &value - )) return NULL; - - PyDict_SetItemString( - type->tp_dict, - key, - value - ); - PyType_Modified(type); - - Py_RETURN_NONE; -} - -static void sigsegv_handler(int signum) { - longjmp( - buf, - 1 - ); -} - - -static PyObject* handle(PyObject* self, PyObject* args) { - PyObject* func; - PyObject* params = NULL; - PyObject* kwargs = NULL; - - if (!PyArg_ParseTuple( - args, - "O|O!O!", - &func, - &PyTuple_Type, - ¶ms, - &PyDict_Type, - &kwargs - ) - ) return NULL; - - if (!params) params = PyTuple_New(0); - if (!kwargs) kwargs = PyDict_New(); - int val = getenv("POINTERSPY_ALLOW_SEGV") ? 0 : setjmp(buf); - - if (val) { - PyFrameObject* frame = PyEval_GetFrame(); - PyObject* name; - PyCodeObject* code = NULL; - puts("1"); - if (frame) { - code = GET_CODE(frame); - name = Py_NewRef(code->co_name); - } else { - name = PyObject_GetAttrString( - func, - "__name__" - ); - } - puts("2"); - - Py_DECREF(frame); - - PyErr_Format( - PyExc_RuntimeError, - "segment violation occured during execution of %S", - name - ); - - if (code) Py_DECREF(code); - return NULL; - } - - PyObject* result = PyObject_Call( - func, - params, - kwargs - ); - if (!result) return NULL; - return result; -} - -static PyObject* run_stack_callback(PyObject* self, PyObject* args) { - int size; - PyObject* tp; - PyObject* func; - - if (!PyArg_ParseTuple( - args, - "iO!O", - &size, - &PyType_Type, - &tp, - &func - )) return NULL; - - void* ptr = ALLOCA(size); - PyObject* tp_args = PyTuple_New(2); - PyTuple_SetItem( - tp_args, - 0, - PyLong_FromVoidPtr(ptr) - ); - PyTuple_SetItem( - tp_args, - 1, - PyLong_FromLong(size) - ); - PyObject* obj = PyObject_Call( - tp, - tp_args, - NULL - ); - if (!obj) return NULL; - - PyObject* tup = PyTuple_New(1); - PyTuple_SetItem( - tup, - 0, - obj - ); - PyObject* result = PyObject_Call( - func, - tup, - NULL - ); - if (!result) return NULL; - PyObject_SetAttrString( - obj, - "freed", - Py_True - ); - - Py_INCREF(result); - return result; -} - -static PyObject* force_update_locals(PyObject* self, PyObject* args) { - PyFrameObject* f; - PyObject* key; - PyObject* value; - - if (!PyArg_ParseTuple( - args, - "O!UO", - &PyFrame_Type, - &f, - &key, - &value - )) - return NULL; - - PyObject* locals = GET_LOCALS(f); - if (PyDict_SetItem( - locals, - key, - value - ) < 0) - return NULL; - - PyFrame_LocalsToFast( - f, - 1 - ); - Py_RETURN_NONE; -} - -static PyMethodDef methods[] = { - {"add_ref", add_ref, METH_VARARGS, - "Increment the reference count on the target object."}, - {"remove_ref", remove_ref, METH_VARARGS, - "Decrement the reference count on the target object."}, - {"force_set_attr", force_set_attr, METH_VARARGS, - "Force setting an attribute on the target type."}, - {"set_ref", set_ref, METH_VARARGS, - "Set the reference count on the target object."}, - {"handle", handle, METH_VARARGS, "Enable the SIGSEGV handler."}, - {"run_stack_callback", run_stack_callback, METH_VARARGS, - "Run a callback with a stack allocated pointer."}, - {"force_update_locals", force_update_locals, METH_VARARGS, - "Force update the locals of the target frame."}, - {NULL, NULL, 0, NULL} -}; - -static struct PyModuleDef module = { - PyModuleDef_HEAD_INIT, - "_pointers", - NULL, - -1, - methods -}; - -void sigabrt_handler(int signum) { - Py_FatalError( - "python aborted! this means you have a memory error somewhere!" - ); -} - -PyMODINIT_FUNC PyInit__pointers(void) { - if (signal( - SIGABRT, - sigabrt_handler - ) == SIG_ERR) { - PyErr_SetString( - PyExc_ImportError, - "cant load _pointers: failed to setup SIGABRT handler" - ); - return NULL; - }; - if (signal( - SIGSEGV, - sigsegv_handler - ) == SIG_ERR) { - PyErr_SetString( - PyExc_ImportError, - "cant load _pointers: failed to setup SIGSEGV handler" - ); - return NULL; - } - - return PyModule_Create(&module); -} diff --git a/src/pointers/__init__.py b/src/pointers/__init__.py index bfcbc69..03371f2 100644 --- a/src/pointers/__init__.py +++ b/src/pointers/__init__.py @@ -1,38 +1,5 @@ -if __import__("sys").implementation.name != "cpython": - # using __import__ to make sure sys isnt exported - raise Exception( - "pointers.py is only supported on cpython", - ) - -from ._utils import force_set_attr -from .api_bindings import * -from .base_pointers import ( - BaseAllocatedPointer, BaseCPointer, BaseObjectPointer, BasePointer, - BasicPointer, Dereferencable, IterDereferencable, Sized -) -from .bindings import * -from .c_pointer import ( - TypedCPointer, VoidPointer, array, cast, to_c_ptr, to_func_ptr, - to_struct_ptr, to_voidp -) -from .calloc import AllocatedArrayPointer, calloc -from .custom_binding import binding, binds -from .decay import decay, decay_annotated, decay_wrapped -from .exceptions import ( - AllocationError, DereferenceError, FreedMemoryError, - InvalidBindingParameter, InvalidSizeError, NullPointerError, - SegmentViolation, VariableLifetimeError -) -from .magic import _ -from .malloc import AllocatedPointer, free, malloc, realloc -from .object_pointer import Pointer, to_ptr -from .stack_pointer import ( - StackAllocatedPointer, acquire_stack_alloc, stack_alloc -) -from .std_structs import DivT, Lconv, LDivT, Tm -from .structure import Struct, StructPointer -from .util import NULL, Nullable, handle, raw_type, struct_cast, stop_handler -from .var_pointer import VarPointer, to_var_ptr - -__version__ = "3.0.0" -__license__ = "MIT" +from .exceptions import * +from .pointer import * + +__author__ = "Peter Bierma" +__license__ = "MIT" diff --git a/src/pointers/_cstd.py b/src/pointers/_cstd.py deleted file mode 100644 index 9d9cf7b..0000000 --- a/src/pointers/_cstd.py +++ /dev/null @@ -1,550 +0,0 @@ -import ctypes -from ctypes.util import find_library -from sys import platform - -__all__ = ( - "c_malloc", - "c_free", - "c_realloc", - "c_calloc", - "dll", - "tm", - "lconv", - "div_t", - "ldiv_t", -) - -_c_library_name: str - -if platform in ("win32", "cygwin"): - _c_library_name = "msvcrt" -elif platform == "darwin": - _c_library_name = "libc.dylib" -else: - _c_library_name = find_library("c") or "libc.so.6" - -dll = ctypes.CDLL(_c_library_name) -mdll = ( - dll - if platform in ("win32", "cygwin") - else ctypes.CDLL( - find_library("m") or ( - "libm.dylib" if platform == "darwin" else "libm.so.6" - ) - ) -) - - -class tm(ctypes.Structure): - _fields_ = [ - ("tm_sec", ctypes.c_int), - ("tm_min", ctypes.c_int), - ("tm_hour", ctypes.c_int), - ("tm_mday", ctypes.c_int), - ("tm_mon", ctypes.c_int), - ("tm_year", ctypes.c_int), - ("tm_wday", ctypes.c_int), - ("tm_yday", ctypes.c_int), - ("tm_isdst", ctypes.c_int), - ] - - -class div_t(ctypes.Structure): - _fields_ = [ - ("quot", ctypes.c_int), - ("rem", ctypes.c_int), - ] - - -class ldiv_t(ctypes.Structure): - _fields_ = [ - ("quot", ctypes.c_long), - ("rem", ctypes.c_long), - ] - - -class lconv(ctypes.Structure): - _fields_ = [ - ("decimal_point", ctypes.c_char_p), - ("thousands_sep", ctypes.c_char_p), - ("grouping", ctypes.c_char_p), - ("int_curr_symbol", ctypes.c_char_p), - ("currency_symbol", ctypes.c_char_p), - ("mon_decimal_point", ctypes.c_char_p), - ("mon_thousands_sep", ctypes.c_char_p), - ("mon_grouping", ctypes.c_char_p), - ("positive_sign", ctypes.c_char_p), - ("negative_sign", ctypes.c_char_p), - ("int_frac_digits", ctypes.c_char), - ("frac_digits", ctypes.c_char), - ("p_cs_precedes", ctypes.c_char), - ("p_sep_by_space", ctypes.c_char), - ("n_sep_by_space", ctypes.c_char), - ("p_sign_posn", ctypes.c_char), - ("n_sign_posn", ctypes.c_char), - ] - - -c_raise = getattr(dll, "raise") - -# void* malloc(size_t size); -dll.malloc.argtypes = (ctypes.c_size_t,) -dll.malloc.restype = ctypes.c_void_p -# void free(void* ptr); -dll.free.argtypes = (ctypes.c_void_p,) -dll.free.restype = None -# void* realloc(void* ptr, size_t size); -dll.realloc.argtypes = (ctypes.c_void_p, ctypes.c_size_t) -dll.realloc.restype = ctypes.c_void_p -# void* calloc (size_t num, size_t size); -dll.calloc.argtypes = (ctypes.c_size_t, ctypes.c_size_t) -dll.calloc.restype = ctypes.c_void_p -# int isalnum(int c) -dll.isalnum.argtypes = (ctypes.c_char,) -dll.isalnum.restype = ctypes.c_int -# int isalpha(int c) -dll.isalpha.argtypes = (ctypes.c_char,) -dll.isalpha.restype = ctypes.c_int -# int iscntrl(int c) -dll.iscntrl.argtypes = (ctypes.c_char,) -dll.iscntrl.restype = ctypes.c_int -# int isdigit(int c) -dll.isdigit.argtypes = (ctypes.c_char,) -dll.isdigit.restype = ctypes.c_int -# int isgraph(int c) -dll.isgraph.argtypes = (ctypes.c_char,) -dll.isgraph.restype = ctypes.c_int -# int islower(int c) -dll.islower.argtypes = (ctypes.c_char,) -dll.islower.restype = ctypes.c_int -# int isprint(int c) -dll.isprint.argtypes = (ctypes.c_char,) -dll.isprint.restype = ctypes.c_int -# int ispunct(int c) -dll.ispunct.argtypes = (ctypes.c_char,) -dll.ispunct.restype = ctypes.c_int -# int isspace(int c) -dll.isspace.argtypes = (ctypes.c_char,) -dll.isspace.restype = ctypes.c_int -# int isupper(int c) -dll.isupper.argtypes = (ctypes.c_char,) -dll.isupper.restype = ctypes.c_int -# int isxdigit(int c) -dll.isxdigit.argtypes = (ctypes.c_char,) -dll.isxdigit.restype = ctypes.c_int -# int tolower(int c) -dll.tolower.argtypes = (ctypes.c_char,) -dll.tolower.restype = ctypes.c_char -# int toupper(int c) -dll.toupper.argtypes = (ctypes.c_char,) -dll.toupper.restype = ctypes.c_char -# char* setlocale(int category, const char* locale) -dll.setlocale.argtypes = (ctypes.c_int, ctypes.c_char_p) -dll.setlocale.restype = ctypes.c_char_p -# struct lconv* localeconv(void) -dll.localeconv.argtypes = () -dll.localeconv.restype = ctypes.POINTER(lconv) -# double frexp(double x, int* exponent) -mdll.frexp.argtypes = ( - ctypes.c_double, - ctypes.POINTER(ctypes.c_int), -) -mdll.frexp.restype = ctypes.c_double -# double ldexp(double x, int exponent) -mdll.ldexp.argtypes = (ctypes.c_double, ctypes.c_int) -mdll.ldexp.restype = ctypes.c_double -# double modf(double x, double* integer) -mdll.modf.argtypes = ( - ctypes.c_double, - ctypes.POINTER(ctypes.c_double), -) -mdll.modf.restype = ctypes.c_double -# int raise(int sig) -c_raise.argtypes = (ctypes.c_int,) -c_raise.restype = ctypes.c_int -# int fclose(FILE* stream) -dll.fclose.argtypes = (ctypes.c_void_p,) -dll.fclose.restype = ctypes.c_int -# void clearerr(FILE* stream) -dll.clearerr.argtypes = (ctypes.c_void_p,) -dll.clearerr.restype = None -# int feof(FILE* stream) -dll.feof.argtypes = (ctypes.c_void_p,) -dll.feof.restype = ctypes.c_int -# int ferror(FILE* stream) -dll.ferror.argtypes = (ctypes.c_void_p,) -dll.ferror.restype = ctypes.c_int -# int fflush(FILE* stream) -dll.fflush.argtypes = (ctypes.c_void_p,) -dll.fflush.restype = ctypes.c_int -# int fgetpos(FILE* stream, fpos_t* pos) -dll.fgetpos.argtypes = (ctypes.c_void_p, ctypes.c_void_p) -dll.fgetpos.restype = ctypes.c_int -# FILE* fopen(const char* filename, const char* mode) -dll.fopen.argtypes = (ctypes.c_char_p, ctypes.c_char_p) -dll.fopen.restype = ctypes.c_void_p -# size_t fread(void* ptr, size_t size, size_t nmemb, FILE* stream) -dll.fread.argtypes = ( - ctypes.c_void_p, - ctypes.c_size_t, - ctypes.c_size_t, -) -dll.fread.restype = ctypes.c_size_t -# FILE* freopen(const char* filename, const char* mode, FILE* stream) -dll.freopen.argtypes = ( - ctypes.c_char_p, - ctypes.c_char_p, - ctypes.c_void_p, -) -dll.freopen.restype = ctypes.c_void_p -# int fseek(FILE* stream, long int offset, int whence) -dll.fseek.argtypes = (ctypes.c_void_p, ctypes.c_long, ctypes.c_int) -dll.fseek.restype = ctypes.c_int -# int fsetpos(FILE* stream, const fpos_t* pos) -dll.fsetpos.argtypes = (ctypes.c_void_p, ctypes.c_void_p) -dll.fsetpos.restype = ctypes.c_int -# long int ftell(FILE* stream) -dll.ftell.argtypes = (ctypes.c_void_p,) -dll.ftell.restype = ctypes.c_long -# size_t fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) -dll.fwrite.argtypes = ( - ctypes.c_void_p, - ctypes.c_size_t, - ctypes.c_size_t, - ctypes.c_void_p, -) -dll.fwrite.restype = ctypes.c_size_t -# int remove(const char* filename) -dll.remove.argtypes = (ctypes.c_char_p,) -dll.remove.restype = ctypes.c_int -# int rename(const char* old_filename, const char* new_filename) -dll.rename.argtypes = (ctypes.c_char_p, ctypes.c_char_p) -dll.rename.restype = ctypes.c_int -# void rewind(FILE* stream) -dll.rewind.argtypes = (ctypes.c_void_p,) -dll.rewind.restype = None -# void setbuf(FILE* stream, char* buffer) -dll.setbuf.argtypes = (ctypes.c_void_p, ctypes.c_char_p) -dll.setbuf.restype = None -# int setvbuf(FILE* stream, char* buffer, int mode, size_t size) -dll.setvbuf.argtypes = ( - ctypes.c_void_p, - ctypes.c_char_p, - ctypes.c_int, - ctypes.c_size_t, -) -dll.setvbuf.restype = ctypes.c_int -# FILE* tmpfile(void) -dll.tmpfile.argtypes = () -dll.tmpfile.restype = ctypes.c_void_p -# char* tmpnam(char* str) -dll.tmpnam.argtypes = (ctypes.c_char_p,) -dll.tmpnam.restype = ctypes.c_char_p -# int fprintf(FILE* stream, const char* format, ...) -dll.fprintf.restype = ctypes.c_int -# int printf(const char* format, ...) -dll.printf.restype = ctypes.c_int -# int sprintf(char* str, const char* format, ...) -dll.sprintf.restype = ctypes.c_int -# int vfprintf(FILE* stream, const char* format, va_list arg) -# int vprintf(const char* format, va_list arg) -# int vsprintf(char* str, const char* format, va_list arg) -# int fscanf(FILE* stream, const char* format, ...) -dll.fscanf.restype = ctypes.c_int -# int scanf(const char* format, ...) -dll.scanf.argtypes = (ctypes.c_char_p,) -dll.scanf.restype = ctypes.c_int -# int sscanf(const char* str, const char* format, ...) -dll.sscanf.restype = ctypes.c_int -# int fgetc(FILE* stream) -dll.fgetc.argtypes = (ctypes.c_void_p,) -dll.fgetc.restype = ctypes.c_int -# char* fgets(char* str, int n, FILE* stream) -dll.fgets.argtypes = (ctypes.c_char_p, ctypes.c_int, ctypes.c_void_p) -dll.fgets.restype = ctypes.c_char_p -# int fputc(int char, FILE* stream) -dll.fputc.argtypes = (ctypes.c_char, ctypes.c_void_p) -dll.fputc.restype = ctypes.c_int -# int fputs(const char* str, FILE* stream) -dll.fputs.argtypes = (ctypes.c_char_p, ctypes.c_void_p) -dll.fputs.restype = ctypes.c_int -# int getc(FILE* stream) -dll.getc.argtypes = (ctypes.c_void_p,) -dll.getc.restype = ctypes.c_int -# int getchar(void) -dll.getchar.argtypes = () -dll.getchar.restype = ctypes.c_int -# char* gets(char* str) -dll.gets.argtypes = (ctypes.c_char_p,) -dll.gets.restype = ctypes.c_char_p -# int putc(int char, FILE* stream) -dll.putc.argtypes = (ctypes.c_char, ctypes.c_void_p) -dll.putc.restype = ctypes.c_int -# int putchar(int char) -dll.putchar.argtypes = (ctypes.c_char,) -dll.putchar.restype = ctypes.c_int -# int puts(const char* str) -dll.puts.argtypes = (ctypes.c_char_p,) -dll.puts.restype = ctypes.c_int -# int ungetc(int char, FILE* stream) -dll.ungetc.argtypes = ( - ctypes.c_char, - ctypes.c_void_p, -) -dll.ungetc.restype = ctypes.c_int -# void perror(const char* str) -dll.perror.argtypes = (ctypes.c_char_p,) -dll.perror.restype = None -# double strtod(const char* str, char** endptr) -dll.strtod.argtypes = (ctypes.c_char_p, ctypes.POINTER(ctypes.c_char_p)) -dll.strtod.restype = ctypes.c_double -# long int strtol(const char* str, char** endptr, int base) -dll.strtol.argtypes = ( - ctypes.c_char_p, - ctypes.POINTER(ctypes.c_char_p), - ctypes.c_int, -) -dll.strtol.restype = ctypes.c_long -# unsigned long int strtoul(const char* str, char** endptr, int base) -dll.strtoul.argtypes = ( - ctypes.c_char_p, - ctypes.POINTER(ctypes.c_char_p), - ctypes.c_int, -) -dll.strtoul.restype = ctypes.c_ulong -# void abort(void) -dll.abort.argtypes = () -dll.abort.restype = None -# void exit(int status) -dll.exit.argtypes = (ctypes.c_int,) -dll.exit.restype = None -# char* getenv(const char* name) -dll.getenv.argtypes = (ctypes.c_char_p,) -dll.getenv.restype = ctypes.c_char_p -# int system(const char* string) -dll.system.argtypes = (ctypes.c_char_p,) -dll.system.restype = ctypes.c_int -# int abs(int x) -dll.abs.argtypes = (ctypes.c_int,) -dll.abs.restype = ctypes.c_int -# div_t div(int numer, int denom) -dll.div.argtypes = (ctypes.c_int, ctypes.c_int) -dll.div.restype = div_t -# long int labs(long int x) -dll.labs.argtypes = (ctypes.c_long,) -dll.labs.restype = ctypes.c_long -# ldiv_t ldiv(long int numer, long int denom) -dll.ldiv.argtypes = (ctypes.c_long, ctypes.c_long) -dll.ldiv.restype = ldiv_t -# int rand(void) -dll.rand.argtypes = () -dll.rand.restype = ctypes.c_int -# void srand(unsigned int seed) -dll.srand.argtypes = (ctypes.c_long,) -dll.srand.restype = None -# int mblen(const char* str, size_t n) -dll.mblen.argtypes = (ctypes.c_char_p, ctypes.c_size_t) -dll.mblen.restype = ctypes.c_int -# size_t mbstowcs(wchar_t* pwcs, const char* str, size_t n) -dll.mbstowcs.argtypes = ( - ctypes.c_wchar_p, - ctypes.c_char_p, - ctypes.c_size_t, -) -dll.mbstowcs.restype = ctypes.c_size_t -# int mbtowc(wchar_t* pwc, const char* str, size_t n) -dll.mbtowc.argtypes = ( - ctypes.c_wchar_p, - ctypes.c_char_p, - ctypes.c_size_t, -) -dll.mbtowc.restype = ctypes.c_int -# size_t wcstombs(char* str, const wchar_t* pwcs, size_t n) -dll.wcstombs.argtypes = ( - ctypes.c_char_p, - ctypes.c_wchar_p, - ctypes.c_size_t, -) -dll.wcstombs.restype = ctypes.c_size_t -# int wctomb(char* str, wchar_t wchar) -dll.wctomb.argtypes = (ctypes.c_char_p, ctypes.c_wchar_p) -dll.wctomb.restype = ctypes.c_int -# void* memchr(const void* str, int c, size_t n) -dll.memchr.argtypes = ( - ctypes.c_void_p, - ctypes.c_int, - ctypes.c_size_t, -) -dll.memchr.restype = ctypes.c_void_p -# int memcmp(const void* str1, const void* str2, size_t n) -dll.memcmp.argtypes = ( - ctypes.c_void_p, - ctypes.c_void_p, - ctypes.c_size_t, -) -dll.memcmp.restype = ctypes.c_int -# void* memcpy(void* dest, const void* src, size_t n) -dll.memcpy.argtypes = ( - ctypes.c_void_p, - ctypes.c_void_p, - ctypes.c_size_t, -) -dll.memcpy.restype = ctypes.c_void_p -# void* memmove(void* dest, const void* src, size_t n) -dll.memmove.argtypes = ( - ctypes.c_void_p, - ctypes.c_void_p, - ctypes.c_size_t, -) -dll.memmove.restype = ctypes.c_void_p -# void* memset(void* str, int c, size_t n) -dll.memset.argtypes = ( - ctypes.c_void_p, - ctypes.c_int, - ctypes.c_size_t, -) -dll.memset.restype = ctypes.c_void_p -# char* strcat(char* dest, const char* src) -dll.strcat.argtypes = (ctypes.c_char_p, ctypes.c_char_p) -dll.strcat.restype = ctypes.c_char_p -# char* strncat(char* dest, const char* src, size_t n) -dll.strncat.argtypes = ( - ctypes.c_char_p, - ctypes.c_char_p, - ctypes.c_size_t, -) -dll.strncat.restype = ctypes.c_char_p -# char* strchr(const char* str, int c) -dll.strchr.argtypes = (ctypes.c_char_p, ctypes.c_int) -dll.strchr.restype = ctypes.c_char_p -# int strcmp(const char* str1, const char* str2) -dll.strcmp.argtypes = (ctypes.c_char_p, ctypes.c_char_p) -dll.strcmp.restype = ctypes.c_int -# int strncmp(const char* str1, const char* str2, size_t n) -dll.strncmp.argtypes = (ctypes.c_char_p, ctypes.c_char_p) -dll.strncmp.restype = ctypes.c_int -# int strcoll(const char* str1, const char* str2) -dll.strcoll.argtypes = (ctypes.c_char_p, ctypes.c_char_p) -dll.strcoll.restype = ctypes.c_int -# char* strcpy(char* dest, const char* src) -dll.strcpy.argtypes = (ctypes.c_char_p, ctypes.c_char_p) -dll.strcpy.restype = ctypes.c_char_p -# char* strncpy(char* dest, const char* src, size_t n) -dll.strncpy.argtypes = ( - ctypes.c_char_p, - ctypes.c_char_p, - ctypes.c_size_t, -) -dll.strncpy.restype = ctypes.c_char_p -# size_t strcspn(const char* str1, const char* str2) -dll.strcspn.argtypes = (ctypes.c_char_p, ctypes.c_char_p) -dll.strcspn.restype = ctypes.c_size_t -# char* strerror(int errnum) -dll.strerror.argtypes = (ctypes.c_int,) -dll.strerror.restype = ctypes.c_char_p -# size_t strlen(const char* str) -dll.strlen.argtypes = (ctypes.c_char_p,) -dll.strlen.restype = ctypes.c_size_t -# char* strpbrk(const char* str1, const char* str2) -dll.strpbrk.argtypes = (ctypes.c_char_p, ctypes.c_char_p) -dll.strpbrk.restype = ctypes.c_char_p -# char* strrchr(const char* str, int c) -dll.strrchr.argtypes = (ctypes.c_char_p, ctypes.c_int) -dll.strrchr.restype = ctypes.c_char_p -# size_t strspn(const char* str1, const char* str2) -dll.strspn.argtypes = (ctypes.c_char_p, ctypes.c_char_p) -dll.strspn.restype = ctypes.c_size_t -# char* strstr(const char* haystack, const char* needle) -dll.strstr.argtypes = (ctypes.c_char_p, ctypes.c_char_p) -dll.strstr.restype = ctypes.c_char_p -# char* strtok(char* str, const char* delim) -dll.strstr.argtypes = (ctypes.c_char_p, ctypes.c_char_p) -dll.strtok.restype = ctypes.c_char_p -# size_t strxfrm(char* dest, const char* src, size_t n) -dll.strxfrm.argtypes = ( - ctypes.c_char_p, - ctypes.c_char_p, - ctypes.c_size_t, -) -dll.strxfrm.restype = ctypes.c_size_t -# char* asctime(const struct tm* timeptr) -dll.asctime.argtypes = (ctypes.POINTER(tm),) -dll.asctime.restype = ctypes.c_char_p -# clock_t clock(void) -dll.clock.argtypes = () -dll.clock.restype = ctypes.c_int -# char* ctime(const time_t* timer) -dll.ctime.argtypes = (ctypes.POINTER(ctypes.c_int),) -dll.ctime.restype = ctypes.c_char_p -# double difftime(time_t time1, time_t time2) -dll.difftime.argtypes = (ctypes.c_int, ctypes.c_int) -dll.difftime.restype = ctypes.c_double -# struct tm* gmtime(const time_t* timer) -dll.gmtime.argtypes = (ctypes.POINTER(ctypes.c_int),) -dll.gmtime.restype = ctypes.POINTER(tm) -# struct tm* localtime(const time_t* timer) -dll.localtime.argtypes = (ctypes.c_int,) -dll.localtime.restype = ctypes.POINTER(tm) -# time_t mktime(struct tm* timeptr) -dll.mktime.argtypes = (ctypes.POINTER(tm),) -dll.mktime.restype = ctypes.c_int -# size_t strftime( -# char *str, -# size_t maxsize, -# const char *format, -# const struct tm* timeptr -# ) -dll.strftime.argtypes = ( - ctypes.c_char_p, - ctypes.c_size_t, - ctypes.c_char_p, - ctypes.POINTER(tm), -) -dll.strftime.restype = ctypes.c_size_t -# time_t time(time_t* timer) -dll.time.argtypes = (ctypes.POINTER(ctypes.c_int),) -dll.time.restype = ctypes.c_int -# void (*signal(int sig, void (*func)(int)))(int) -dll.signal.argtypes = (ctypes.c_int, ctypes.CFUNCTYPE(None, ctypes.c_int)) -dll.signal.restype = None -# void qsort( -# void *base, -# size_t nitems, -# size_t size, -# int (*compar)(const void *, const void*) -# ) -dll.qsort.argtypes = ( - ctypes.c_void_p, - ctypes.c_size_t, - ctypes.c_size_t, - ctypes.CFUNCTYPE( - ctypes.c_int, - ctypes.c_void_p, - ctypes.c_void_p, - ), -) -dll.qsort.restype = None -# void *bsearch( -# const void *key, -# const void *base, -# size_t nitems, -# size_t size, -# int (*compar)(const void *, const void *) -# ) -dll.bsearch.argtypes = ( - ctypes.c_void_p, - ctypes.c_void_p, - ctypes.c_size_t, - ctypes.c_size_t, - ctypes.CFUNCTYPE( - ctypes.c_int, - ctypes.c_void_p, - ctypes.c_void_p, - ), -) -dll.bsearch.restype = ctypes.c_void_p - -c_malloc = dll.malloc -c_free = dll.free -c_realloc = dll.realloc -c_calloc = dll.calloc diff --git a/src/pointers/_pyapi.py b/src/pointers/_pyapi.py deleted file mode 100644 index b284c70..0000000 --- a/src/pointers/_pyapi.py +++ /dev/null @@ -1,1566 +0,0 @@ -import ctypes -from ctypes import pythonapi as dll -from typing import Dict, Optional, Tuple, Type - -__all__ = ( - "API_FUNCS", - "Func", -) - -CData = Type["ctypes._CData"] -Func = Tuple[Optional["ctypes._NamedFuncPointer"], Optional[str], str] -API_FUNCS: Dict[str, Func] = {} - - -def _register( - name: str, - restype: Optional[CData], - argtypes: Optional[Tuple[CData, ...]] = None, - *, - minver: Optional[str] = None, -) -> None: - func: Optional["ctypes._NamedFuncPointer"] = getattr(dll, name, None) - - if func: - func.argtypes = argtypes # type: ignore - func.restype = restype - - API_FUNCS[name] = (func, minver, name) - - -class PyTypeObject(ctypes.Structure): - pass - - -class PyThreadState(ctypes.Structure): - pass - - -class PyFrameObject(ctypes.Structure): - pass - - -class PyInterpreterState(ctypes.Structure): - pass - - -class PyVarObject(ctypes.Structure): - _fields_ = [ - ("ob_size", ctypes.c_ssize_t), - ("ob_refcnt", ctypes.c_ssize_t), - ("ob_type", ctypes.POINTER(PyTypeObject)), - ] - - -class PyType_Slot(ctypes.Structure): - _fields_ = [ - ("slot", ctypes.c_int), - ("pfunc", ctypes.c_void_p), - ] - - -class PyType_Spec(ctypes.Structure): - _fields_ = [ - ("name", ctypes.c_char_p), - ("basic_size", ctypes.c_int), - ("itemsize", ctypes.c_int), - ("flags", ctypes.c_int), - ("slots", ctypes.POINTER(PyType_Slot)), - ] - - -class Py_tss_t(ctypes.Structure): - pass - - -class Py_buffer(ctypes.Structure): - _fields_ = [ - ("buf", ctypes.c_void_p), - ("obj", ctypes.c_void_p), - ("len", ctypes.c_ssize_t), - ("readonly", ctypes.c_int), - ("itemsize", ctypes.c_ssize_t), - ("format", ctypes.c_char_p), - ("ndim", ctypes.c_int), - ("shape", ctypes.POINTER(ctypes.c_ssize_t)), - ("strides", ctypes.POINTER(ctypes.c_ssize_t)), - ("suboffsets", ctypes.POINTER(ctypes.c_ssize_t)), - ("internal", ctypes.c_void_p), - ] - - -class PyModuleDef(ctypes.Structure): - _fields_ = [ - ("m_base", ctypes.c_char_p), - ("pfunc", ctypes.c_void_p), - ] - - -class PyCodeObject(ctypes.Structure): - pass - - -class PyMethodDef(ctypes.Structure): - _fields_ = [ - ("ml_name", ctypes.c_char_p), - ("ml_meth", ctypes.CFUNCTYPE(ctypes.py_object, ctypes.py_object)), - ("ml_flags", ctypes.c_int), - ("ml_doc", ctypes.c_char_p), - ] - - -class PyGetSetDef(ctypes.Structure): - _fields_ = [ - ("name", ctypes.c_char_p), - ("get", ctypes.CFUNCTYPE(ctypes.py_object, ctypes.py_object, ctypes.c_void_p)), - ( - "set", - ctypes.CFUNCTYPE( - ctypes.c_int, ctypes.py_object, ctypes.py_object, ctypes.c_void_p - ), - ), - ("doc", ctypes.c_char_p), - ("closure", ctypes.c_void_p), - ] - - -Py_UCS4 = ctypes.c_uint32 - - -# autogenerated - - -# int PyAIter_Check(PyObject* o) -_register('PyAIter_Check', ctypes.c_int, (ctypes.py_object,), minver="3.10",) -# int PyArg_Parse(PyObject* args, const char* format, ...) -_register('PyArg_Parse', ctypes.c_int) -# int PyArg_ParseTuple(PyObject* args, const char* format, ...) -_register('PyArg_ParseTuple', ctypes.c_int) -# int PyArg_ParseTupleAndKeywords(PyObject* args, PyObject* kw, const char* format, char* keywords[], ...) -_register('PyArg_ParseTupleAndKeywords', ctypes.c_int) -# int PyArg_UnpackTuple(PyObject* args, const char* name, Py_ssize_t min, Py_ssize_t max, ...) -_register('PyArg_UnpackTuple', ctypes.c_int) -# int PyArg_VaParse(PyObject* args, const char* format, va_list vargs) -_register('PyArg_VaParse', ctypes.c_int, (ctypes.py_object,ctypes.c_char_p,ctypes.c_void_p,)) -# int PyArg_VaParseTupleAndKeywords(PyObject* args, PyObject* kw, const char* format, char* keywords[], va_list vargs) -_register('PyArg_VaParseTupleAndKeywords', ctypes.c_int, (ctypes.py_object,ctypes.py_object,ctypes.c_char_p,ctypes.POINTER(ctypes.c_char_p),ctypes.c_void_p,)) -# PyObject* PyBool_FromLong(long v) -_register('PyBool_FromLong', ctypes.py_object, (ctypes.c_long,)) -# void PyBuffer_FillContiguousStrides(int ndims, Py_ssize_t* shape, Py_ssize_t* strides, int itemsize, char order) -_register('PyBuffer_FillContiguousStrides', None, (ctypes.c_int,ctypes.POINTER(ctypes.c_ssize_t),ctypes.POINTER(ctypes.c_ssize_t),ctypes.c_int,ctypes.c_char,)) -# int PyBuffer_FillInfo(Py_buffer* view, PyObject* exporter, void* buf, Py_ssize_t len, int readonly, int flags) -_register('PyBuffer_FillInfo', ctypes.c_int, (ctypes.POINTER(Py_buffer),ctypes.py_object,ctypes.c_void_p,ctypes.c_ssize_t,ctypes.c_int,ctypes.c_int,)) -# int PyBuffer_FromContiguous(const Py_buffer* view, const void* buf, Py_ssize_t len, char fort) -_register('PyBuffer_FromContiguous', ctypes.c_int, (ctypes.POINTER(Py_buffer),ctypes.c_void_p,ctypes.c_ssize_t,ctypes.c_char,)) -# void* PyBuffer_GetPointer(const Py_buffer* view, const Py_ssize_t* indices) -_register('PyBuffer_GetPointer', ctypes.c_void_p, (ctypes.POINTER(Py_buffer),ctypes.POINTER(ctypes.c_ssize_t),)) -# int PyBuffer_IsContiguous(const Py_buffer* view, char order) -_register('PyBuffer_IsContiguous', ctypes.c_int, (ctypes.POINTER(Py_buffer),ctypes.c_char,)) -# void PyBuffer_Release(Py_buffer* view) -_register('PyBuffer_Release', None, (ctypes.POINTER(Py_buffer),)) -# Py_ssize_t PyBuffer_SizeFromFormat(const char* format) -_register('PyBuffer_SizeFromFormat', ctypes.c_ssize_t, (ctypes.c_char_p,), minver="3.9",) -# int PyBuffer_ToContiguous(void* buf, const Py_buffer* src, Py_ssize_t len, char order) -_register('PyBuffer_ToContiguous', ctypes.c_int, (ctypes.c_void_p,ctypes.POINTER(Py_buffer),ctypes.c_ssize_t,ctypes.c_char,)) -# char* PyByteArray_AsString(PyObject* bytearray) -_register('PyByteArray_AsString', ctypes.c_char_p, (ctypes.py_object,)) -# PyObject* PyByteArray_Concat(PyObject* a, PyObject* b) -_register('PyByteArray_Concat', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyByteArray_FromObject(PyObject* o) -_register('PyByteArray_FromObject', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyByteArray_FromStringAndSize(const char* string, Py_ssize_t len) -_register('PyByteArray_FromStringAndSize', ctypes.py_object, (ctypes.c_char_p,ctypes.c_ssize_t,)) -# int PyByteArray_Resize(PyObject* bytearray, Py_ssize_t len) -_register('PyByteArray_Resize', ctypes.c_int, (ctypes.py_object,ctypes.c_ssize_t,)) -# Py_ssize_t PyByteArray_Size(PyObject* bytearray) -_register('PyByteArray_Size', ctypes.c_ssize_t, (ctypes.py_object,)) -# char* PyBytes_AsString(PyObject* o) -_register('PyBytes_AsString', ctypes.c_char_p, (ctypes.py_object,)) -# int PyBytes_AsStringAndSize(PyObject* obj, char** buffer, Py_ssize_t* length) -_register('PyBytes_AsStringAndSize', ctypes.c_int, (ctypes.py_object,ctypes.POINTER(ctypes.c_char_p),ctypes.POINTER(ctypes.c_ssize_t),)) -# void PyBytes_Concat(PyObject** bytes, PyObject* newpart) -_register('PyBytes_Concat', None, (ctypes.POINTER(ctypes.py_object),ctypes.py_object,)) -# void PyBytes_ConcatAndDel(PyObject** bytes, PyObject* newpart) -_register('PyBytes_ConcatAndDel', None, (ctypes.POINTER(ctypes.py_object),ctypes.py_object,)) -# PyObject* PyBytes_FromFormat(const char* format, ...) -_register('PyBytes_FromFormat', ctypes.py_object) -# PyObject* PyBytes_FromFormatV(const char* format, va_list vargs) -_register('PyBytes_FromFormatV', ctypes.py_object, (ctypes.c_char_p,ctypes.c_void_p,)) -# PyObject* PyBytes_FromObject(PyObject* o) -_register('PyBytes_FromObject', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyBytes_FromString(const char* v) -_register('PyBytes_FromString', ctypes.py_object, (ctypes.c_char_p,)) -# PyObject* PyBytes_FromStringAndSize(const char* v, Py_ssize_t len) -_register('PyBytes_FromStringAndSize', ctypes.py_object, (ctypes.c_char_p,ctypes.c_ssize_t,)) -# Py_ssize_t PyBytes_Size(PyObject* o) -_register('PyBytes_Size', ctypes.c_ssize_t, (ctypes.py_object,)) -# PyObject* PyCFunction_New(PyMethodDef* ml, PyObject* self) -_register('PyCFunction_New', ctypes.py_object, (ctypes.POINTER(PyMethodDef),ctypes.py_object,)) -# PyObject* PyCFunction_NewEx(PyMethodDef* ml, PyObject* self, PyObject* module) -_register('PyCFunction_NewEx', ctypes.py_object, (ctypes.POINTER(PyMethodDef),ctypes.py_object,ctypes.py_object,)) -# PyObject* PyCMethod_New(PyMethodDef* ml, PyObject* self, PyObject* module, PyTypeObject* cls) -_register('PyCMethod_New', ctypes.py_object, (ctypes.POINTER(PyMethodDef),ctypes.py_object,ctypes.py_object,ctypes.POINTER(PyTypeObject),), minver="3.9",) -# PyObject* PyCallIter_New(PyObject* callable, PyObject* sentinel) -_register('PyCallIter_New', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# int PyCallable_Check(PyObject* o) -_register('PyCallable_Check', ctypes.c_int, (ctypes.py_object,)) -# void* PyCapsule_GetContext(PyObject* capsule) -_register('PyCapsule_GetContext', ctypes.c_void_p, (ctypes.py_object,)) -# PyCapsule_Destructor PyCapsule_GetDestructor(PyObject* capsule) -_register('PyCapsule_GetDestructor', ctypes.c_void_p, (ctypes.py_object,)) -# const char* PyCapsule_GetName(PyObject* capsule) -_register('PyCapsule_GetName', ctypes.c_char_p, (ctypes.py_object,)) -# void* PyCapsule_GetPointer(PyObject* capsule, const char* name) -_register('PyCapsule_GetPointer', ctypes.c_void_p, (ctypes.py_object,ctypes.c_char_p,)) -# void* PyCapsule_Import(const char* name, int no_block) -_register('PyCapsule_Import', ctypes.c_void_p, (ctypes.c_char_p,ctypes.c_int,)) -# int PyCapsule_IsValid(PyObject* capsule, const char* name) -_register('PyCapsule_IsValid', ctypes.c_int, (ctypes.py_object,ctypes.c_char_p,)) -# PyObject* PyCapsule_New(void* pointer, const char* name, PyCapsule_Destructor destructor) -_register('PyCapsule_New', ctypes.py_object, (ctypes.c_void_p,ctypes.c_char_p,ctypes.c_void_p,)) -# int PyCapsule_SetContext(PyObject* capsule, void* context) -_register('PyCapsule_SetContext', ctypes.c_int, (ctypes.py_object,ctypes.c_void_p,)) -# int PyCapsule_SetDestructor(PyObject* capsule, PyCapsule_Destructor destructor) -_register('PyCapsule_SetDestructor', ctypes.c_int, (ctypes.py_object,ctypes.c_void_p,)) -# int PyCapsule_SetName(PyObject* capsule, const char* name) -_register('PyCapsule_SetName', ctypes.c_int, (ctypes.py_object,ctypes.c_char_p,)) -# int PyCapsule_SetPointer(PyObject* capsule, void* pointer) -_register('PyCapsule_SetPointer', ctypes.c_int, (ctypes.py_object,ctypes.c_void_p,)) -# PyObject* PyCodec_BackslashReplaceErrors(PyObject* exc) -_register('PyCodec_BackslashReplaceErrors', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyCodec_Decode(PyObject* object, const char* encoding, const char* errors) -_register('PyCodec_Decode', ctypes.py_object, (ctypes.py_object,ctypes.c_char_p,ctypes.c_char_p,)) -# PyObject* PyCodec_Decoder(const char* encoding) -_register('PyCodec_Decoder', ctypes.py_object, (ctypes.c_char_p,)) -# PyObject* PyCodec_Encode(PyObject* object, const char* encoding, const char* errors) -_register('PyCodec_Encode', ctypes.py_object, (ctypes.py_object,ctypes.c_char_p,ctypes.c_char_p,)) -# PyObject* PyCodec_Encoder(const char* encoding) -_register('PyCodec_Encoder', ctypes.py_object, (ctypes.c_char_p,)) -# PyObject* PyCodec_IgnoreErrors(PyObject* exc) -_register('PyCodec_IgnoreErrors', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyCodec_IncrementalDecoder(const char* encoding, const char* errors) -_register('PyCodec_IncrementalDecoder', ctypes.py_object, (ctypes.c_char_p,ctypes.c_char_p,)) -# PyObject* PyCodec_IncrementalEncoder(const char* encoding, const char* errors) -_register('PyCodec_IncrementalEncoder', ctypes.py_object, (ctypes.c_char_p,ctypes.c_char_p,)) -# int PyCodec_KnownEncoding(const char* encoding) -_register('PyCodec_KnownEncoding', ctypes.c_int, (ctypes.c_char_p,)) -# PyObject* PyCodec_LookupError(const char* name) -_register('PyCodec_LookupError', ctypes.py_object, (ctypes.c_char_p,)) -# PyObject* PyCodec_NameReplaceErrors(PyObject* exc) -_register('PyCodec_NameReplaceErrors', ctypes.py_object, (ctypes.py_object,), minver="3.5",) -# int PyCodec_Register(PyObject* search_function) -_register('PyCodec_Register', ctypes.c_int, (ctypes.py_object,)) -# int PyCodec_RegisterError(const char* name, PyObject* error) -_register('PyCodec_RegisterError', ctypes.c_int, (ctypes.c_char_p,ctypes.py_object,)) -# PyObject* PyCodec_ReplaceErrors(PyObject* exc) -_register('PyCodec_ReplaceErrors', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyCodec_StreamReader(const char* encoding, PyObject* stream, const char* errors) -_register('PyCodec_StreamReader', ctypes.py_object, (ctypes.c_char_p,ctypes.py_object,ctypes.c_char_p,)) -# PyObject* PyCodec_StreamWriter(const char* encoding, PyObject* stream, const char* errors) -_register('PyCodec_StreamWriter', ctypes.py_object, (ctypes.c_char_p,ctypes.py_object,ctypes.c_char_p,)) -# PyObject* PyCodec_StrictErrors(PyObject* exc) -_register('PyCodec_StrictErrors', ctypes.py_object, (ctypes.py_object,)) -# int PyCodec_Unregister(PyObject* search_function) -_register('PyCodec_Unregister', ctypes.c_int, (ctypes.py_object,), minver="3.10",) -# PyObject* PyCodec_XMLCharRefReplaceErrors(PyObject* exc) -_register('PyCodec_XMLCharRefReplaceErrors', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyComplex_FromDoubles(double real, double imag) -_register('PyComplex_FromDoubles', ctypes.py_object, (ctypes.c_double,ctypes.c_double,)) -# double PyComplex_ImagAsDouble(PyObject* op) -_register('PyComplex_ImagAsDouble', ctypes.c_double, (ctypes.py_object,)) -# double PyComplex_RealAsDouble(PyObject* op) -_register('PyComplex_RealAsDouble', ctypes.c_double, (ctypes.py_object,)) -# PyObject* PyDescr_NewClassMethod(PyTypeObject* type, PyMethodDef* method) -_register('PyDescr_NewClassMethod', ctypes.py_object, (ctypes.POINTER(PyTypeObject),ctypes.POINTER(PyMethodDef),)) -# PyObject* PyDescr_NewGetSet(PyTypeObject* type, PyGetSetDef* getset) -_register('PyDescr_NewGetSet', ctypes.py_object, (ctypes.POINTER(PyTypeObject),ctypes.POINTER(PyGetSetDef),)) -# PyObject* PyDescr_NewMember(PyTypeObject* type, PyMemberDef* meth) -_register('PyDescr_NewMember', ctypes.py_object, (ctypes.POINTER(PyTypeObject),)) -# PyObject* PyDescr_NewMethod(PyTypeObject* type, PyMethodDef* meth) -_register('PyDescr_NewMethod', ctypes.py_object, (ctypes.POINTER(PyTypeObject),ctypes.POINTER(PyMethodDef),)) -# PyObject* PyDictProxy_New(PyObject* mapping) -_register('PyDictProxy_New', ctypes.py_object, (ctypes.py_object,)) -# void PyDict_Clear(PyObject* p) -_register('PyDict_Clear', None, (ctypes.py_object,)) -# int PyDict_Contains(PyObject* p, PyObject* key) -_register('PyDict_Contains', ctypes.c_int, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyDict_Copy(PyObject* p) -_register('PyDict_Copy', ctypes.py_object, (ctypes.py_object,)) -# int PyDict_DelItem(PyObject* p, PyObject* key) -_register('PyDict_DelItem', ctypes.c_int, (ctypes.py_object,ctypes.py_object,)) -# int PyDict_DelItemString(PyObject* p, const char* key) -_register('PyDict_DelItemString', ctypes.c_int, (ctypes.py_object,ctypes.c_char_p,)) -# PyObject* PyDict_GetItem(PyObject* p, PyObject* key) -_register('PyDict_GetItem', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyDict_GetItemString(PyObject* p, const char* key) -_register('PyDict_GetItemString', ctypes.py_object, (ctypes.py_object,ctypes.c_char_p,)) -# PyObject* PyDict_GetItemWithError(PyObject* p, PyObject* key) -_register('PyDict_GetItemWithError', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyDict_Items(PyObject* p) -_register('PyDict_Items', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyDict_Keys(PyObject* p) -_register('PyDict_Keys', ctypes.py_object, (ctypes.py_object,)) -# int PyDict_Merge(PyObject* a, PyObject* b, int override) -_register('PyDict_Merge', ctypes.c_int, (ctypes.py_object,ctypes.py_object,ctypes.c_int,)) -# int PyDict_MergeFromSeq2(PyObject* a, PyObject* seq2, int override) -_register('PyDict_MergeFromSeq2', ctypes.c_int, (ctypes.py_object,ctypes.py_object,ctypes.c_int,)) -# PyObject* PyDict_New() -_register('PyDict_New', ctypes.py_object, ()) -# int PyDict_Next(PyObject* p, Py_ssize_t* ppos, PyObject** pkey, PyObject** pvalue) -_register('PyDict_Next', ctypes.c_int, (ctypes.py_object,ctypes.POINTER(ctypes.c_ssize_t),ctypes.POINTER(ctypes.py_object),ctypes.POINTER(ctypes.py_object),)) -# int PyDict_SetItem(PyObject* p, PyObject* key, PyObject* val) -_register('PyDict_SetItem', ctypes.c_int, (ctypes.py_object,ctypes.py_object,ctypes.py_object,)) -# int PyDict_SetItemString(PyObject* p, const char* key, PyObject* val) -_register('PyDict_SetItemString', ctypes.c_int, (ctypes.py_object,ctypes.c_char_p,ctypes.py_object,)) -# Py_ssize_t PyDict_Size(PyObject* p) -_register('PyDict_Size', ctypes.c_ssize_t, (ctypes.py_object,)) -# int PyDict_Update(PyObject* a, PyObject* b) -_register('PyDict_Update', ctypes.c_int, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyDict_Values(PyObject* p) -_register('PyDict_Values', ctypes.py_object, (ctypes.py_object,)) -# int PyErr_BadArgument() -_register('PyErr_BadArgument', ctypes.c_int, ()) -# void PyErr_BadInternalCall() -_register('PyErr_BadInternalCall', None, ()) -# int PyErr_CheckSignals() -_register('PyErr_CheckSignals', ctypes.c_int, ()) -# void PyErr_Clear() -_register('PyErr_Clear', None, ()) -# int PyErr_ExceptionMatches(PyObject* exc) -_register('PyErr_ExceptionMatches', ctypes.c_int, (ctypes.py_object,)) -# void PyErr_Fetch(PyObject** ptype, PyObject** pvalue, PyObject** ptraceback) -_register('PyErr_Fetch', None, (ctypes.POINTER(ctypes.py_object),ctypes.POINTER(ctypes.py_object),ctypes.POINTER(ctypes.py_object),)) -# PyObject* PyErr_Format(PyObject* exception, const char* format, ...) -_register('PyErr_Format', ctypes.py_object) -# PyObject* PyErr_FormatV(PyObject* exception, const char* format, va_list vargs) -_register('PyErr_FormatV', ctypes.py_object, (ctypes.py_object,ctypes.c_char_p,ctypes.c_void_p,), minver="3.5",) -# void PyErr_GetExcInfo(PyObject** ptype, PyObject** pvalue, PyObject** ptraceback) -_register('PyErr_GetExcInfo', None, (ctypes.POINTER(ctypes.py_object),ctypes.POINTER(ctypes.py_object),ctypes.POINTER(ctypes.py_object),), minver="3.3",) -# PyObject* PyErr_GetHandledException(void) -_register('PyErr_GetHandledException', ctypes.py_object, (), minver="3.11",) -# int PyErr_GivenExceptionMatches(PyObject* given, PyObject* exc) -_register('PyErr_GivenExceptionMatches', ctypes.c_int, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyErr_NewException(const char* name, PyObject* base, PyObject* dict) -_register('PyErr_NewException', ctypes.py_object, (ctypes.c_char_p,ctypes.py_object,ctypes.py_object,)) -# PyObject* PyErr_NewExceptionWithDoc(const char* name, const char* doc, PyObject* base, PyObject* dict) -_register('PyErr_NewExceptionWithDoc', ctypes.py_object, (ctypes.c_char_p,ctypes.c_char_p,ctypes.py_object,ctypes.py_object,), minver="3.2",) -# PyObject* PyErr_NoMemory() -_register('PyErr_NoMemory', ctypes.py_object, ()) -# void PyErr_NormalizeException(PyObject** exc, PyObject** val, PyObject** tb) -_register('PyErr_NormalizeException', None, (ctypes.POINTER(ctypes.py_object),ctypes.POINTER(ctypes.py_object),ctypes.POINTER(ctypes.py_object),)) -# PyObject* PyErr_Occurred() -_register('PyErr_Occurred', ctypes.py_object, ()) -# void PyErr_Print() -_register('PyErr_Print', None, ()) -# void PyErr_PrintEx(int set_sys_last_vars) -_register('PyErr_PrintEx', None, (ctypes.c_int,)) -# int PyErr_ResourceWarning(PyObject* source, Py_ssize_t stack_level, const char* format, ...) -_register('PyErr_ResourceWarning', ctypes.c_int, minver="3.6",) -# void PyErr_Restore(PyObject* type, PyObject* value, PyObject* traceback) -_register('PyErr_Restore', None, (ctypes.py_object,ctypes.py_object,ctypes.py_object,)) -# PyObject* PyErr_SetExcFromWindowsErr(PyObject* type, int ierr) -_register('PyErr_SetExcFromWindowsErr', ctypes.py_object, (ctypes.py_object,ctypes.c_int,)) -# PyObject* PyErr_SetExcFromWindowsErrWithFilename(PyObject* type, int ierr, const char* filename) -_register('PyErr_SetExcFromWindowsErrWithFilename', ctypes.py_object, (ctypes.py_object,ctypes.c_int,ctypes.c_char_p,)) -# PyObject* PyErr_SetExcFromWindowsErrWithFilenameObject(PyObject* type, int ierr, PyObject* filename) -_register('PyErr_SetExcFromWindowsErrWithFilenameObject', ctypes.py_object, (ctypes.py_object,ctypes.c_int,ctypes.py_object,)) -# PyObject* PyErr_SetExcFromWindowsErrWithFilenameObjects(PyObject* type, int ierr, PyObject* filename, PyObject* filename2) -_register('PyErr_SetExcFromWindowsErrWithFilenameObjects', ctypes.py_object, (ctypes.py_object,ctypes.c_int,ctypes.py_object,ctypes.py_object,), minver="3.4",) -# void PyErr_SetExcInfo(PyObject* type, PyObject* value, PyObject* traceback) -_register('PyErr_SetExcInfo', None, (ctypes.py_object,ctypes.py_object,ctypes.py_object,), minver="3.3",) -# PyObject* PyErr_SetFromErrno(PyObject* type) -_register('PyErr_SetFromErrno', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyErr_SetFromErrnoWithFilename(PyObject* type, const char* filename) -_register('PyErr_SetFromErrnoWithFilename', ctypes.py_object, (ctypes.py_object,ctypes.c_char_p,)) -# PyObject* PyErr_SetFromErrnoWithFilenameObject(PyObject* type, PyObject* filenameObject) -_register('PyErr_SetFromErrnoWithFilenameObject', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyErr_SetFromErrnoWithFilenameObjects(PyObject* type, PyObject* filenameObject, PyObject* filenameObject2) -_register('PyErr_SetFromErrnoWithFilenameObjects', ctypes.py_object, (ctypes.py_object,ctypes.py_object,ctypes.py_object,), minver="3.4",) -# PyObject* PyErr_SetFromWindowsErr(int ierr) -_register('PyErr_SetFromWindowsErr', ctypes.py_object, (ctypes.c_int,)) -# PyObject* PyErr_SetFromWindowsErrWithFilename(int ierr, const char* filename) -_register('PyErr_SetFromWindowsErrWithFilename', ctypes.py_object, (ctypes.c_int,ctypes.c_char_p,)) -# void PyErr_SetHandledException(PyObject* exc) -_register('PyErr_SetHandledException', None, (ctypes.py_object,), minver="3.11",) -# PyObject* PyErr_SetImportError(PyObject* msg, PyObject* name, PyObject* path) -_register('PyErr_SetImportError', ctypes.py_object, (ctypes.py_object,ctypes.py_object,ctypes.py_object,), minver="3.3",) -# PyObject* PyErr_SetImportErrorSubclass(PyObject* exception, PyObject* msg, PyObject* name, PyObject* path) -_register('PyErr_SetImportErrorSubclass', ctypes.py_object, (ctypes.py_object,ctypes.py_object,ctypes.py_object,ctypes.py_object,), minver="3.6",) -# void PyErr_SetInterrupt() -_register('PyErr_SetInterrupt', None, ()) -# int PyErr_SetInterruptEx(int signum) -_register('PyErr_SetInterruptEx', ctypes.c_int, (ctypes.c_int,), minver="3.10",) -# void PyErr_SetNone(PyObject* type) -_register('PyErr_SetNone', None, (ctypes.py_object,)) -# void PyErr_SetObject(PyObject* type, PyObject* value) -_register('PyErr_SetObject', None, (ctypes.py_object,ctypes.py_object,)) -# void PyErr_SetString(PyObject* type, const char* message) -_register('PyErr_SetString', None, (ctypes.py_object,ctypes.c_char_p,)) -# void PyErr_SyntaxLocation(const char* filename, int lineno) -_register('PyErr_SyntaxLocation', None, (ctypes.c_char_p,ctypes.c_int,)) -# void PyErr_SyntaxLocationEx(const char* filename, int lineno, int col_offset) -_register('PyErr_SyntaxLocationEx', None, (ctypes.c_char_p,ctypes.c_int,ctypes.c_int,), minver="3.2",) -# int PyErr_WarnEx(PyObject* category, const char* message, Py_ssize_t stack_level) -_register('PyErr_WarnEx', ctypes.c_int, (ctypes.py_object,ctypes.c_char_p,ctypes.c_ssize_t,)) -# int PyErr_WarnExplicit(PyObject* category, const char* message, const char* filename, int lineno, const char* module, PyObject* registry) -_register('PyErr_WarnExplicit', ctypes.c_int, (ctypes.py_object,ctypes.c_char_p,ctypes.c_char_p,ctypes.c_int,ctypes.c_char_p,ctypes.py_object,)) -# int PyErr_WarnFormat(PyObject* category, Py_ssize_t stack_level, const char* format, ...) -_register('PyErr_WarnFormat', ctypes.c_int, minver="3.2",) -# void PyErr_WriteUnraisable(PyObject* obj) -_register('PyErr_WriteUnraisable', None, (ctypes.py_object,)) -# void PyEval_AcquireLock() -_register('PyEval_AcquireLock', None, ()) -# void PyEval_AcquireThread(PyThreadState* tstate) -_register('PyEval_AcquireThread', None, (ctypes.POINTER(PyThreadState),)) -# PyObject* PyEval_EvalCode(PyObject* co, PyObject* globals, PyObject* locals) -_register('PyEval_EvalCode', ctypes.py_object, (ctypes.py_object,ctypes.py_object,ctypes.py_object,)) -# PyObject* PyEval_EvalCodeEx(PyObject* co, PyObject* globals, PyObject* locals, PyObject* const* args, int argcount, PyObject* const* kws, int kwcount, PyObject* const* defs, int defcount, PyObject* kwdefs, PyObject* closure) -_register('PyEval_EvalCodeEx', ctypes.py_object, (ctypes.py_object,ctypes.py_object,ctypes.py_object,ctypes.POINTER(ctypes.py_object),ctypes.c_int,ctypes.POINTER(ctypes.py_object),ctypes.c_int,ctypes.POINTER(ctypes.py_object),ctypes.c_int,ctypes.py_object,ctypes.py_object,)) -# PyObject* PyEval_EvalFrame(PyFrameObject* f) -_register('PyEval_EvalFrame', ctypes.py_object, (ctypes.POINTER(PyFrameObject),)) -# PyObject* PyEval_EvalFrameEx(PyFrameObject* f, int throwflag) -_register('PyEval_EvalFrameEx', ctypes.py_object, (ctypes.POINTER(PyFrameObject),ctypes.c_int,)) -# PyObject* PyEval_GetBuiltins(void) -_register('PyEval_GetBuiltins', ctypes.py_object, ()) -# PyFrameObject* PyEval_GetFrame(void) -_register('PyEval_GetFrame', ctypes.POINTER(PyFrameObject), ()) -# const char* PyEval_GetFuncDesc(PyObject* func) -_register('PyEval_GetFuncDesc', ctypes.c_char_p, (ctypes.py_object,)) -# const char* PyEval_GetFuncName(PyObject* func) -_register('PyEval_GetFuncName', ctypes.c_char_p, (ctypes.py_object,)) -# PyObject* PyEval_GetGlobals(void) -_register('PyEval_GetGlobals', ctypes.py_object, ()) -# PyObject* PyEval_GetLocals(void) -_register('PyEval_GetLocals', ctypes.py_object, ()) -# void PyEval_InitThreads() -_register('PyEval_InitThreads', None, ()) -# void PyEval_ReleaseLock() -_register('PyEval_ReleaseLock', None, ()) -# void PyEval_ReleaseThread(PyThreadState* tstate) -_register('PyEval_ReleaseThread', None, (ctypes.POINTER(PyThreadState),)) -# void PyEval_RestoreThread(PyThreadState* tstate) -_register('PyEval_RestoreThread', None, (ctypes.POINTER(PyThreadState),)) -# PyThreadState* PyEval_SaveThread() -_register('PyEval_SaveThread', ctypes.POINTER(PyThreadState), ()) -# int PyEval_ThreadsInitialized() -_register('PyEval_ThreadsInitialized', ctypes.c_int, ()) -# PyObject* PyException_GetCause(PyObject* ex) -_register('PyException_GetCause', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyException_GetContext(PyObject* ex) -_register('PyException_GetContext', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyException_GetTraceback(PyObject* ex) -_register('PyException_GetTraceback', ctypes.py_object, (ctypes.py_object,)) -# void PyException_SetCause(PyObject* ex, PyObject* cause) -_register('PyException_SetCause', None, (ctypes.py_object,ctypes.py_object,)) -# void PyException_SetContext(PyObject* ex, PyObject* ctx) -_register('PyException_SetContext', None, (ctypes.py_object,ctypes.py_object,)) -# int PyException_SetTraceback(PyObject* ex, PyObject* tb) -_register('PyException_SetTraceback', ctypes.c_int, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyFile_FromFd(int fd, const char* name, const char* mode, int buffering, const char* encoding, const char* errors, const char* newline, int closefd) -_register('PyFile_FromFd', ctypes.py_object, (ctypes.c_int,ctypes.c_char_p,ctypes.c_char_p,ctypes.c_int,ctypes.c_char_p,ctypes.c_char_p,ctypes.c_char_p,ctypes.c_int,)) -# PyObject* PyFile_GetLine(PyObject* p, int n) -_register('PyFile_GetLine', ctypes.py_object, (ctypes.py_object,ctypes.c_int,)) -# int PyFile_WriteObject(PyObject* obj, PyObject* p, int flags) -_register('PyFile_WriteObject', ctypes.c_int, (ctypes.py_object,ctypes.py_object,ctypes.c_int,)) -# int PyFile_WriteString(const char* s, PyObject* p) -_register('PyFile_WriteString', ctypes.c_int, (ctypes.c_char_p,ctypes.py_object,)) -# double PyFloat_AsDouble(PyObject* pyfloat) -_register('PyFloat_AsDouble', ctypes.c_double, (ctypes.py_object,)) -# PyObject* PyFloat_FromDouble(double v) -_register('PyFloat_FromDouble', ctypes.py_object, (ctypes.c_double,)) -# PyObject* PyFloat_FromString(PyObject* str) -_register('PyFloat_FromString', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyFloat_GetInfo(void) -_register('PyFloat_GetInfo', ctypes.py_object, ()) -# double PyFloat_GetMax() -_register('PyFloat_GetMax', ctypes.c_double, ()) -# double PyFloat_GetMin() -_register('PyFloat_GetMin', ctypes.c_double, ()) -# PyCodeObject* PyFrame_GetCode(PyFrameObject* frame) -_register('PyFrame_GetCode', ctypes.POINTER(PyCodeObject), (ctypes.POINTER(PyFrameObject),), minver="3.9",) -# int PyFrame_GetLineNumber(PyFrameObject* frame) -_register('PyFrame_GetLineNumber', ctypes.c_int, (ctypes.POINTER(PyFrameObject),)) -# PyObject* PyFrozenSet_New(PyObject* iterable) -_register('PyFrozenSet_New', ctypes.py_object, (ctypes.py_object,)) -# Py_ssize_t PyGC_Collect(void) -_register('PyGC_Collect', ctypes.c_ssize_t, ()) -# int PyGC_Disable(void) -_register('PyGC_Disable', ctypes.c_int, (), minver="3.10",) -# int PyGC_Enable(void) -_register('PyGC_Enable', ctypes.c_int, (), minver="3.10",) -# int PyGC_IsEnabled(void) -_register('PyGC_IsEnabled', ctypes.c_int, (), minver="3.10",) -# PyGILState_STATE PyGILState_Ensure() -_register('PyGILState_Ensure', ctypes.c_int, ()) -# PyThreadState* PyGILState_GetThisThreadState() -_register('PyGILState_GetThisThreadState', ctypes.POINTER(PyThreadState), ()) -# PyObject* PyImport_AddModule(const char* name) -_register('PyImport_AddModule', ctypes.py_object, (ctypes.c_char_p,)) -# PyObject* PyImport_AddModuleObject(PyObject* name) -_register('PyImport_AddModuleObject', ctypes.py_object, (ctypes.py_object,), minver="3.3",) -# PyObject* PyImport_ExecCodeModule(const char* name, PyObject* co) -_register('PyImport_ExecCodeModule', ctypes.py_object, (ctypes.c_char_p,ctypes.py_object,)) -# PyObject* PyImport_ExecCodeModuleEx(const char* name, PyObject* co, const char* pathname) -_register('PyImport_ExecCodeModuleEx', ctypes.py_object, (ctypes.c_char_p,ctypes.py_object,ctypes.c_char_p,)) -# PyObject* PyImport_ExecCodeModuleObject(PyObject* name, PyObject* co, PyObject* pathname, PyObject* cpathname) -_register('PyImport_ExecCodeModuleObject', ctypes.py_object, (ctypes.py_object,ctypes.py_object,ctypes.py_object,ctypes.py_object,), minver="3.3",) -# PyObject* PyImport_ExecCodeModuleWithPathnames(const char* name, PyObject* co, const char* pathname, const char* cpathname) -_register('PyImport_ExecCodeModuleWithPathnames', ctypes.py_object, (ctypes.c_char_p,ctypes.py_object,ctypes.c_char_p,ctypes.c_char_p,), minver="3.2",) -# PyObject* PyImport_GetImporter(PyObject* path) -_register('PyImport_GetImporter', ctypes.py_object, (ctypes.py_object,)) -# long PyImport_GetMagicNumber() -_register('PyImport_GetMagicNumber', ctypes.c_long, ()) -# const char* PyImport_GetMagicTag() -_register('PyImport_GetMagicTag', ctypes.c_char_p, (), minver="3.2",) -# PyObject* PyImport_GetModule(PyObject* name) -_register('PyImport_GetModule', ctypes.py_object, (ctypes.py_object,), minver="3.7",) -# PyObject* PyImport_GetModuleDict() -_register('PyImport_GetModuleDict', ctypes.py_object, ()) -# PyObject* PyImport_Import(PyObject* name) -_register('PyImport_Import', ctypes.py_object, (ctypes.py_object,)) -# int PyImport_ImportFrozenModule(const char* name) -_register('PyImport_ImportFrozenModule', ctypes.c_int, (ctypes.c_char_p,)) -# int PyImport_ImportFrozenModuleObject(PyObject* name) -_register('PyImport_ImportFrozenModuleObject', ctypes.c_int, (ctypes.py_object,), minver="3.3",) -# PyObject* PyImport_ImportModule(const char* name) -_register('PyImport_ImportModule', ctypes.py_object, (ctypes.c_char_p,)) -# PyObject* PyImport_ImportModuleLevel(const char* name, PyObject* globals, PyObject* locals, PyObject* fromlist, int level) -_register('PyImport_ImportModuleLevel', ctypes.py_object, (ctypes.c_char_p,ctypes.py_object,ctypes.py_object,ctypes.py_object,ctypes.c_int,)) -# PyObject* PyImport_ImportModuleLevelObject(PyObject* name, PyObject* globals, PyObject* locals, PyObject* fromlist, int level) -_register('PyImport_ImportModuleLevelObject', ctypes.py_object, (ctypes.py_object,ctypes.py_object,ctypes.py_object,ctypes.py_object,ctypes.c_int,), minver="3.3",) -# PyObject* PyImport_ImportModuleNoBlock(const char* name) -_register('PyImport_ImportModuleNoBlock', ctypes.py_object, (ctypes.c_char_p,)) -# PyObject* PyImport_ReloadModule(PyObject* m) -_register('PyImport_ReloadModule', ctypes.py_object, (ctypes.py_object,)) -# int PyIndex_Check(PyObject* o) -_register('PyIndex_Check', ctypes.c_int, (ctypes.py_object,)) -# void PyInterpreterState_Clear(PyInterpreterState* interp) -_register('PyInterpreterState_Clear', None, (ctypes.POINTER(PyInterpreterState),)) -# void PyInterpreterState_Delete(PyInterpreterState* interp) -_register('PyInterpreterState_Delete', None, (ctypes.POINTER(PyInterpreterState),)) -# PyInterpreterState* PyInterpreterState_Get(void) -_register('PyInterpreterState_Get', ctypes.POINTER(PyInterpreterState), (), minver="3.9",) -# PyObject* PyInterpreterState_GetDict(PyInterpreterState* interp) -_register('PyInterpreterState_GetDict', ctypes.py_object, (ctypes.POINTER(PyInterpreterState),), minver="3.8",) -# int64_t PyInterpreterState_GetID(PyInterpreterState* interp) -_register('PyInterpreterState_GetID', ctypes.c_int64, (ctypes.POINTER(PyInterpreterState),), minver="3.7",) -# PyInterpreterState* PyInterpreterState_New() -_register('PyInterpreterState_New', ctypes.POINTER(PyInterpreterState), ()) -# int PyIter_Check(PyObject* o) -_register('PyIter_Check', ctypes.c_int, (ctypes.py_object,)) -# PyObject* PyIter_Next(PyObject* o) -_register('PyIter_Next', ctypes.py_object, (ctypes.py_object,)) -# PySendResult PyIter_Send(PyObject* iter, PyObject* arg, PyObject** presult) -_register('PyIter_Send', ctypes.c_int, (ctypes.py_object,ctypes.py_object,ctypes.POINTER(ctypes.py_object),), minver="3.10",) -# int PyList_Append(PyObject* list, PyObject* item) -_register('PyList_Append', ctypes.c_int, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyList_AsTuple(PyObject* list) -_register('PyList_AsTuple', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyList_GetItem(PyObject* list, Py_ssize_t index) -_register('PyList_GetItem', ctypes.py_object, (ctypes.py_object,ctypes.c_ssize_t,)) -# PyObject* PyList_GetSlice(PyObject* list, Py_ssize_t low, Py_ssize_t high) -_register('PyList_GetSlice', ctypes.py_object, (ctypes.py_object,ctypes.c_ssize_t,ctypes.c_ssize_t,)) -# int PyList_Insert(PyObject* list, Py_ssize_t index, PyObject* item) -_register('PyList_Insert', ctypes.c_int, (ctypes.py_object,ctypes.c_ssize_t,ctypes.py_object,)) -# PyObject* PyList_New(Py_ssize_t len) -_register('PyList_New', ctypes.py_object, (ctypes.c_ssize_t,)) -# int PyList_Reverse(PyObject* list) -_register('PyList_Reverse', ctypes.c_int, (ctypes.py_object,)) -# int PyList_SetItem(PyObject* list, Py_ssize_t index, PyObject* item) -_register('PyList_SetItem', ctypes.c_int, (ctypes.py_object,ctypes.c_ssize_t,ctypes.py_object,)) -# int PyList_SetSlice(PyObject* list, Py_ssize_t low, Py_ssize_t high, PyObject* itemlist) -_register('PyList_SetSlice', ctypes.c_int, (ctypes.py_object,ctypes.c_ssize_t,ctypes.c_ssize_t,ctypes.py_object,)) -# Py_ssize_t PyList_Size(PyObject* list) -_register('PyList_Size', ctypes.c_ssize_t, (ctypes.py_object,)) -# int PyList_Sort(PyObject* list) -_register('PyList_Sort', ctypes.c_int, (ctypes.py_object,)) -# double PyLong_AsDouble(PyObject* pylong) -_register('PyLong_AsDouble', ctypes.c_double, (ctypes.py_object,)) -# long PyLong_AsLong(PyObject* obj) -_register('PyLong_AsLong', ctypes.c_long, (ctypes.py_object,)) -# long PyLong_AsLongAndOverflow(PyObject* obj, int* overflow) -_register('PyLong_AsLongAndOverflow', ctypes.c_long, (ctypes.py_object,ctypes.POINTER(ctypes.c_int),)) -# long long PyLong_AsLongLong(PyObject* obj) -_register('PyLong_AsLongLong', ctypes.c_longlong, (ctypes.py_object,)) -# long long PyLong_AsLongLongAndOverflow(PyObject* obj, int* overflow) -_register('PyLong_AsLongLongAndOverflow', ctypes.c_longlong, (ctypes.py_object,ctypes.POINTER(ctypes.c_int),), minver="3.2",) -# size_t PyLong_AsSize_t(PyObject* pylong) -_register('PyLong_AsSize_t', ctypes.c_size_t, (ctypes.py_object,)) -# Py_ssize_t PyLong_AsSsize_t(PyObject* pylong) -_register('PyLong_AsSsize_t', ctypes.c_ssize_t, (ctypes.py_object,)) -# unsigned long PyLong_AsUnsignedLong(PyObject* pylong) -_register('PyLong_AsUnsignedLong', ctypes.c_ulong, (ctypes.py_object,)) -# unsigned long long PyLong_AsUnsignedLongLong(PyObject* pylong) -_register('PyLong_AsUnsignedLongLong', ctypes.c_ulonglong, (ctypes.py_object,)) -# unsigned long long PyLong_AsUnsignedLongLongMask(PyObject* obj) -_register('PyLong_AsUnsignedLongLongMask', ctypes.c_ulonglong, (ctypes.py_object,)) -# unsigned long PyLong_AsUnsignedLongMask(PyObject* obj) -_register('PyLong_AsUnsignedLongMask', ctypes.c_ulong, (ctypes.py_object,)) -# void* PyLong_AsVoidPtr(PyObject* pylong) -_register('PyLong_AsVoidPtr', ctypes.c_void_p, (ctypes.py_object,)) -# PyObject* PyLong_FromDouble(double v) -_register('PyLong_FromDouble', ctypes.py_object, (ctypes.c_double,)) -# PyObject* PyLong_FromLong(long v) -_register('PyLong_FromLong', ctypes.py_object, (ctypes.c_long,)) -# PyObject* PyLong_FromLongLong(long long v) -_register('PyLong_FromLongLong', ctypes.py_object, (ctypes.c_longlong,)) -# PyObject* PyLong_FromSize_t(size_t v) -_register('PyLong_FromSize_t', ctypes.py_object, (ctypes.c_size_t,)) -# PyObject* PyLong_FromSsize_t(Py_ssize_t v) -_register('PyLong_FromSsize_t', ctypes.py_object, (ctypes.c_ssize_t,)) -# PyObject* PyLong_FromString(const char* str, char** pend, int base) -_register('PyLong_FromString', ctypes.py_object, (ctypes.c_char_p,ctypes.POINTER(ctypes.c_char_p),ctypes.c_int,)) -# PyObject* PyLong_FromUnsignedLong(unsigned long v) -_register('PyLong_FromUnsignedLong', ctypes.py_object, (ctypes.c_ulong,)) -# PyObject* PyLong_FromUnsignedLongLong(unsigned long long v) -_register('PyLong_FromUnsignedLongLong', ctypes.py_object, (ctypes.c_ulonglong,)) -# PyObject* PyLong_FromVoidPtr(void* p) -_register('PyLong_FromVoidPtr', ctypes.py_object, (ctypes.c_void_p,)) -# int PyMapping_Check(PyObject* o) -_register('PyMapping_Check', ctypes.c_int, (ctypes.py_object,)) -# PyObject* PyMapping_GetItemString(PyObject* o, const char* key) -_register('PyMapping_GetItemString', ctypes.py_object, (ctypes.py_object,ctypes.c_char_p,)) -# int PyMapping_HasKey(PyObject* o, PyObject* key) -_register('PyMapping_HasKey', ctypes.c_int, (ctypes.py_object,ctypes.py_object,)) -# int PyMapping_HasKeyString(PyObject* o, const char* key) -_register('PyMapping_HasKeyString', ctypes.c_int, (ctypes.py_object,ctypes.c_char_p,)) -# PyObject* PyMapping_Items(PyObject* o) -_register('PyMapping_Items', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyMapping_Keys(PyObject* o) -_register('PyMapping_Keys', ctypes.py_object, (ctypes.py_object,)) -# Py_ssize_t PyMapping_Length(PyObject* o) -_register('PyMapping_Length', ctypes.c_ssize_t, (ctypes.py_object,)) -# int PyMapping_SetItemString(PyObject* o, const char* key, PyObject* v) -_register('PyMapping_SetItemString', ctypes.c_int, (ctypes.py_object,ctypes.c_char_p,ctypes.py_object,)) -# Py_ssize_t PyMapping_Size(PyObject* o) -_register('PyMapping_Size', ctypes.c_ssize_t, (ctypes.py_object,)) -# PyObject* PyMapping_Values(PyObject* o) -_register('PyMapping_Values', ctypes.py_object, (ctypes.py_object,)) -# void* PyMem_Calloc(size_t nelem, size_t elsize) -_register('PyMem_Calloc', ctypes.c_void_p, (ctypes.c_size_t,ctypes.c_size_t,), minver="3.5",) -# void PyMem_Free(void* p) -_register('PyMem_Free', None, (ctypes.c_void_p,)) -# void* PyMem_Malloc(size_t n) -_register('PyMem_Malloc', ctypes.c_void_p, (ctypes.c_size_t,)) -# void* PyMem_Realloc(void* p, size_t n) -_register('PyMem_Realloc', ctypes.c_void_p, (ctypes.c_void_p,ctypes.c_size_t,)) -# PyObject* PyMemoryView_FromBuffer(const Py_buffer* view) -_register('PyMemoryView_FromBuffer', ctypes.py_object, (ctypes.POINTER(Py_buffer),)) -# PyObject* PyMemoryView_FromMemory(char* mem, Py_ssize_t size, int flags) -_register('PyMemoryView_FromMemory', ctypes.py_object, (ctypes.c_char_p,ctypes.c_ssize_t,ctypes.c_int,), minver="3.3",) -# PyObject* PyMemoryView_FromObject(PyObject* obj) -_register('PyMemoryView_FromObject', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyMemoryView_GetContiguous(PyObject* obj, int buffertype, char order) -_register('PyMemoryView_GetContiguous', ctypes.py_object, (ctypes.py_object,ctypes.c_int,ctypes.c_char,)) -# PyObject* PyModuleDef_Init(PyModuleDef* def) -_register('PyModuleDef_Init', ctypes.py_object, (ctypes.POINTER(PyModuleDef),), minver="3.5",) -# int PyModule_AddFunctions(PyObject* module, PyMethodDef* functions) -_register('PyModule_AddFunctions', ctypes.c_int, (ctypes.py_object,ctypes.POINTER(PyMethodDef),), minver="3.5",) -# int PyModule_AddIntConstant(PyObject* module, const char* name, long value) -_register('PyModule_AddIntConstant', ctypes.c_int, (ctypes.py_object,ctypes.c_char_p,ctypes.c_long,)) -# int PyModule_AddObject(PyObject* module, const char* name, PyObject* value) -_register('PyModule_AddObject', ctypes.c_int, (ctypes.py_object,ctypes.c_char_p,ctypes.py_object,)) -# int PyModule_AddObjectRef(PyObject* module, const char* name, PyObject* value) -_register('PyModule_AddObjectRef', ctypes.c_int, (ctypes.py_object,ctypes.c_char_p,ctypes.py_object,), minver="3.10",) -# int PyModule_AddStringConstant(PyObject* module, const char* name, const char* value) -_register('PyModule_AddStringConstant', ctypes.c_int, (ctypes.py_object,ctypes.c_char_p,ctypes.c_char_p,)) -# int PyModule_AddType(PyObject* module, PyTypeObject* type) -_register('PyModule_AddType', ctypes.c_int, (ctypes.py_object,ctypes.POINTER(PyTypeObject),), minver="3.9",) -# PyObject* PyModule_Create2(PyModuleDef* def, int module_api_version) -_register('PyModule_Create2', ctypes.py_object, (ctypes.POINTER(PyModuleDef),ctypes.c_int,)) -# int PyModule_ExecDef(PyObject* module, PyModuleDef* def) -_register('PyModule_ExecDef', ctypes.c_int, (ctypes.py_object,ctypes.POINTER(PyModuleDef),), minver="3.5",) -# PyObject* PyModule_FromDefAndSpec2(PyModuleDef* def, PyObject* spec, int module_api_version) -_register('PyModule_FromDefAndSpec2', ctypes.py_object, (ctypes.POINTER(PyModuleDef),ctypes.py_object,ctypes.c_int,), minver="3.5",) -# PyModuleDef* PyModule_GetDef(PyObject* module) -_register('PyModule_GetDef', ctypes.POINTER(PyModuleDef), (ctypes.py_object,)) -# PyObject* PyModule_GetDict(PyObject* module) -_register('PyModule_GetDict', ctypes.py_object, (ctypes.py_object,)) -# const char* PyModule_GetFilename(PyObject* module) -_register('PyModule_GetFilename', ctypes.c_char_p, (ctypes.py_object,)) -# PyObject* PyModule_GetFilenameObject(PyObject* module) -_register('PyModule_GetFilenameObject', ctypes.py_object, (ctypes.py_object,), minver="3.2",) -# const char* PyModule_GetName(PyObject* module) -_register('PyModule_GetName', ctypes.c_char_p, (ctypes.py_object,)) -# PyObject* PyModule_GetNameObject(PyObject* module) -_register('PyModule_GetNameObject', ctypes.py_object, (ctypes.py_object,), minver="3.3",) -# void* PyModule_GetState(PyObject* module) -_register('PyModule_GetState', ctypes.c_void_p, (ctypes.py_object,)) -# PyObject* PyModule_New(const char* name) -_register('PyModule_New', ctypes.py_object, (ctypes.c_char_p,)) -# PyObject* PyModule_NewObject(PyObject* name) -_register('PyModule_NewObject', ctypes.py_object, (ctypes.py_object,), minver="3.3",) -# int PyModule_SetDocString(PyObject* module, const char* docstring) -_register('PyModule_SetDocString', ctypes.c_int, (ctypes.py_object,ctypes.c_char_p,), minver="3.5",) -# PyObject* PyNumber_Absolute(PyObject* o) -_register('PyNumber_Absolute', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyNumber_Add(PyObject* o1, PyObject* o2) -_register('PyNumber_Add', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyNumber_And(PyObject* o1, PyObject* o2) -_register('PyNumber_And', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# Py_ssize_t PyNumber_AsSsize_t(PyObject* o, PyObject* exc) -_register('PyNumber_AsSsize_t', ctypes.c_ssize_t, (ctypes.py_object,ctypes.py_object,)) -# int PyNumber_Check(PyObject* o) -_register('PyNumber_Check', ctypes.c_int, (ctypes.py_object,)) -# PyObject* PyNumber_Divmod(PyObject* o1, PyObject* o2) -_register('PyNumber_Divmod', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyNumber_Float(PyObject* o) -_register('PyNumber_Float', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyNumber_FloorDivide(PyObject* o1, PyObject* o2) -_register('PyNumber_FloorDivide', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyNumber_InPlaceAdd(PyObject* o1, PyObject* o2) -_register('PyNumber_InPlaceAdd', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyNumber_InPlaceAnd(PyObject* o1, PyObject* o2) -_register('PyNumber_InPlaceAnd', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyNumber_InPlaceFloorDivide(PyObject* o1, PyObject* o2) -_register('PyNumber_InPlaceFloorDivide', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyNumber_InPlaceLshift(PyObject* o1, PyObject* o2) -_register('PyNumber_InPlaceLshift', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyNumber_InPlaceMatrixMultiply(PyObject* o1, PyObject* o2) -_register('PyNumber_InPlaceMatrixMultiply', ctypes.py_object, (ctypes.py_object,ctypes.py_object,), minver="3.5",) -# PyObject* PyNumber_InPlaceMultiply(PyObject* o1, PyObject* o2) -_register('PyNumber_InPlaceMultiply', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyNumber_InPlaceOr(PyObject* o1, PyObject* o2) -_register('PyNumber_InPlaceOr', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyNumber_InPlacePower(PyObject* o1, PyObject* o2, PyObject* o3) -_register('PyNumber_InPlacePower', ctypes.py_object, (ctypes.py_object,ctypes.py_object,ctypes.py_object,)) -# PyObject* PyNumber_InPlaceRemainder(PyObject* o1, PyObject* o2) -_register('PyNumber_InPlaceRemainder', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyNumber_InPlaceRshift(PyObject* o1, PyObject* o2) -_register('PyNumber_InPlaceRshift', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyNumber_InPlaceSubtract(PyObject* o1, PyObject* o2) -_register('PyNumber_InPlaceSubtract', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyNumber_InPlaceTrueDivide(PyObject* o1, PyObject* o2) -_register('PyNumber_InPlaceTrueDivide', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyNumber_InPlaceXor(PyObject* o1, PyObject* o2) -_register('PyNumber_InPlaceXor', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyNumber_Index(PyObject* o) -_register('PyNumber_Index', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyNumber_Invert(PyObject* o) -_register('PyNumber_Invert', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyNumber_Long(PyObject* o) -_register('PyNumber_Long', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyNumber_Lshift(PyObject* o1, PyObject* o2) -_register('PyNumber_Lshift', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyNumber_MatrixMultiply(PyObject* o1, PyObject* o2) -_register('PyNumber_MatrixMultiply', ctypes.py_object, (ctypes.py_object,ctypes.py_object,), minver="3.5",) -# PyObject* PyNumber_Multiply(PyObject* o1, PyObject* o2) -_register('PyNumber_Multiply', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyNumber_Negative(PyObject* o) -_register('PyNumber_Negative', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyNumber_Or(PyObject* o1, PyObject* o2) -_register('PyNumber_Or', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyNumber_Positive(PyObject* o) -_register('PyNumber_Positive', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyNumber_Power(PyObject* o1, PyObject* o2, PyObject* o3) -_register('PyNumber_Power', ctypes.py_object, (ctypes.py_object,ctypes.py_object,ctypes.py_object,)) -# PyObject* PyNumber_Remainder(PyObject* o1, PyObject* o2) -_register('PyNumber_Remainder', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyNumber_Rshift(PyObject* o1, PyObject* o2) -_register('PyNumber_Rshift', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyNumber_Subtract(PyObject* o1, PyObject* o2) -_register('PyNumber_Subtract', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyNumber_ToBase(PyObject* n, int base) -_register('PyNumber_ToBase', ctypes.py_object, (ctypes.py_object,ctypes.c_int,)) -# PyObject* PyNumber_TrueDivide(PyObject* o1, PyObject* o2) -_register('PyNumber_TrueDivide', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyNumber_Xor(PyObject* o1, PyObject* o2) -_register('PyNumber_Xor', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# void PyOS_AfterFork() -_register('PyOS_AfterFork', None, ()) -# void PyOS_AfterFork_Child() -_register('PyOS_AfterFork_Child', None, (), minver="3.7",) -# void PyOS_AfterFork_Parent() -_register('PyOS_AfterFork_Parent', None, (), minver="3.7",) -# void PyOS_BeforeFork() -_register('PyOS_BeforeFork', None, (), minver="3.7",) -# int PyOS_CheckStack() -_register('PyOS_CheckStack', ctypes.c_int, ()) -# PyObject* PyOS_FSPath(PyObject* path) -_register('PyOS_FSPath', ctypes.py_object, (ctypes.py_object,), minver="3.6",) -# char* PyOS_double_to_string(double val, char format_code, int precision, int flags, int* ptype) -_register('PyOS_double_to_string', ctypes.c_char_p, (ctypes.c_double,ctypes.c_char,ctypes.c_int,ctypes.c_int,ctypes.POINTER(ctypes.c_int),), minver="3.1",) -# PyOS_sighandler_t PyOS_getsig(int i) -_register('PyOS_getsig', ctypes.c_void_p, (ctypes.c_int,)) -# PyOS_sighandler_t PyOS_setsig(int i, PyOS_sighandler_t h) -_register('PyOS_setsig', ctypes.c_void_p, (ctypes.c_int,ctypes.c_void_p,)) -# int PyOS_snprintf(char* str, size_t size, const char* format, ...) -_register('PyOS_snprintf', ctypes.c_int) -# double PyOS_string_to_double(const char* s, char** endptr, PyObject* overflow_exception) -_register('PyOS_string_to_double', ctypes.c_double, (ctypes.c_char_p,ctypes.POINTER(ctypes.c_char_p),ctypes.py_object,), minver="3.1",) -# long PyOS_strtol(const char* str, char** ptr, int base) -_register('PyOS_strtol', ctypes.c_long, (ctypes.c_char_p,ctypes.POINTER(ctypes.c_char_p),ctypes.c_int,), minver="3.2",) -# unsigned long PyOS_strtoul(const char* str, char** ptr, int base) -_register('PyOS_strtoul', ctypes.c_ulong, (ctypes.c_char_p,ctypes.POINTER(ctypes.c_char_p),ctypes.c_int,), minver="3.2",) -# int PyOS_vsnprintf(char* str, size_t size, const char* format, va_list va) -_register('PyOS_vsnprintf', ctypes.c_int, (ctypes.c_char_p,ctypes.c_size_t,ctypes.c_char_p,ctypes.c_void_p,)) -# PyObject* PyObject_ASCII(PyObject* o) -_register('PyObject_ASCII', ctypes.py_object, (ctypes.py_object,)) -# int PyObject_AsCharBuffer(PyObject* obj, const char** buffer, Py_ssize_t* buffer_len) -_register('PyObject_AsCharBuffer', ctypes.c_int, (ctypes.py_object,ctypes.POINTER(ctypes.c_char_p),ctypes.POINTER(ctypes.c_ssize_t),)) -# int PyObject_AsFileDescriptor(PyObject* p) -_register('PyObject_AsFileDescriptor', ctypes.c_int, (ctypes.py_object,)) -# int PyObject_AsReadBuffer(PyObject* obj, const void** buffer, Py_ssize_t* buffer_len) -_register('PyObject_AsReadBuffer', ctypes.c_int, (ctypes.py_object,ctypes.POINTER(ctypes.c_void_p),ctypes.POINTER(ctypes.c_ssize_t),)) -# int PyObject_AsWriteBuffer(PyObject* obj, void** buffer, Py_ssize_t* buffer_len) -_register('PyObject_AsWriteBuffer', ctypes.c_int, (ctypes.py_object,ctypes.POINTER(ctypes.c_void_p),ctypes.POINTER(ctypes.c_ssize_t),)) -# PyObject* PyObject_Bytes(PyObject* o) -_register('PyObject_Bytes', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyObject_Call(PyObject* callable, PyObject* args, PyObject* kwargs) -_register('PyObject_Call', ctypes.py_object, (ctypes.py_object,ctypes.py_object,ctypes.py_object,)) -# PyObject* PyObject_CallFunction(PyObject* callable, const char* format, ...) -_register('PyObject_CallFunction', ctypes.py_object) -# PyObject* PyObject_CallFunctionObjArgs(PyObject* callable, ...) -_register('PyObject_CallFunctionObjArgs', ctypes.py_object) -# PyObject* PyObject_CallMethod(PyObject* obj, const char* name, const char* format, ...) -_register('PyObject_CallMethod', ctypes.py_object) -# PyObject* PyObject_CallMethodObjArgs(PyObject* obj, PyObject* name, ...) -_register('PyObject_CallMethodObjArgs', ctypes.py_object) -# PyObject* PyObject_CallNoArgs(PyObject* callable) -_register('PyObject_CallNoArgs', ctypes.py_object, (ctypes.py_object,), minver="3.9",) -# PyObject* PyObject_CallObject(PyObject* callable, PyObject* args) -_register('PyObject_CallObject', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# void* PyObject_Calloc(size_t nelem, size_t elsize) -_register('PyObject_Calloc', ctypes.c_void_p, (ctypes.c_size_t,ctypes.c_size_t,), minver="3.5",) -# int PyObject_CheckBuffer(PyObject* obj) -_register('PyObject_CheckBuffer', ctypes.c_int, (ctypes.py_object,)) -# int PyObject_CheckReadBuffer(PyObject* o) -_register('PyObject_CheckReadBuffer', ctypes.c_int, (ctypes.py_object,)) -# void PyObject_ClearWeakRefs(PyObject* object) -_register('PyObject_ClearWeakRefs', None, (ctypes.py_object,)) -# int PyObject_CopyData(PyObject* dest, PyObject* src) -_register('PyObject_CopyData', ctypes.c_int, (ctypes.py_object,ctypes.py_object,)) -# int PyObject_DelItem(PyObject* o, PyObject* key) -_register('PyObject_DelItem', ctypes.c_int, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyObject_Dir(PyObject* o) -_register('PyObject_Dir', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyObject_Format(PyObject* obj, PyObject* format_spec) -_register('PyObject_Format', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# void PyObject_Free(void* p) -_register('PyObject_Free', None, (ctypes.c_void_p,)) -# void PyObject_GC_Del(void* op) -_register('PyObject_GC_Del', None, (ctypes.c_void_p,)) -# int PyObject_GC_IsFinalized(PyObject* op) -_register('PyObject_GC_IsFinalized', ctypes.c_int, (ctypes.py_object,), minver="3.9",) -# int PyObject_GC_IsTracked(PyObject* op) -_register('PyObject_GC_IsTracked', ctypes.c_int, (ctypes.py_object,), minver="3.9",) -# void PyObject_GC_Track(PyObject* op) -_register('PyObject_GC_Track', None, (ctypes.py_object,)) -# void PyObject_GC_UnTrack(void* op) -_register('PyObject_GC_UnTrack', None, (ctypes.c_void_p,)) -# PyObject* PyObject_GenericGetAttr(PyObject* o, PyObject* name) -_register('PyObject_GenericGetAttr', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyObject_GenericGetDict(PyObject* o, void* context) -_register('PyObject_GenericGetDict', ctypes.py_object, (ctypes.py_object,ctypes.c_void_p,), minver="3.3",) -# int PyObject_GenericSetAttr(PyObject* o, PyObject* name, PyObject* value) -_register('PyObject_GenericSetAttr', ctypes.c_int, (ctypes.py_object,ctypes.py_object,ctypes.py_object,)) -# int PyObject_GenericSetDict(PyObject* o, PyObject* value, void* context) -_register('PyObject_GenericSetDict', ctypes.c_int, (ctypes.py_object,ctypes.py_object,ctypes.c_void_p,), minver="3.3",) -# PyObject* PyObject_GetAIter(PyObject* o) -_register('PyObject_GetAIter', ctypes.py_object, (ctypes.py_object,), minver="3.10",) -# PyObject* PyObject_GetAttr(PyObject* o, PyObject* attr_name) -_register('PyObject_GetAttr', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyObject_GetAttrString(PyObject* o, const char* attr_name) -_register('PyObject_GetAttrString', ctypes.py_object, (ctypes.py_object,ctypes.c_char_p,)) -# int PyObject_GetBuffer(PyObject* exporter, Py_buffer* view, int flags) -_register('PyObject_GetBuffer', ctypes.c_int, (ctypes.py_object,ctypes.POINTER(Py_buffer),ctypes.c_int,)) -# PyObject* PyObject_GetItem(PyObject* o, PyObject* key) -_register('PyObject_GetItem', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyObject_GetIter(PyObject* o) -_register('PyObject_GetIter', ctypes.py_object, (ctypes.py_object,)) -# int PyObject_HasAttr(PyObject* o, PyObject* attr_name) -_register('PyObject_HasAttr', ctypes.c_int, (ctypes.py_object,ctypes.py_object,)) -# int PyObject_HasAttrString(PyObject* o, const char* attr_name) -_register('PyObject_HasAttrString', ctypes.c_int, (ctypes.py_object,ctypes.c_char_p,)) -# Py_hash_t PyObject_Hash(PyObject* o) -_register('PyObject_Hash', ctypes.c_ssize_t, (ctypes.py_object,)) -# Py_hash_t PyObject_HashNotImplemented(PyObject* o) -_register('PyObject_HashNotImplemented', ctypes.c_ssize_t, (ctypes.py_object,)) -# PyObject* PyObject_Init(PyObject* op, PyTypeObject* type) -_register('PyObject_Init', ctypes.py_object, (ctypes.py_object,ctypes.POINTER(PyTypeObject),)) -# PyVarObject* PyObject_InitVar(PyVarObject* op, PyTypeObject* type, Py_ssize_t size) -_register('PyObject_InitVar', ctypes.POINTER(PyVarObject), (ctypes.POINTER(PyVarObject),ctypes.POINTER(PyTypeObject),ctypes.c_ssize_t,)) -# int PyObject_IsInstance(PyObject* inst, PyObject* cls) -_register('PyObject_IsInstance', ctypes.c_int, (ctypes.py_object,ctypes.py_object,)) -# int PyObject_IsSubclass(PyObject* derived, PyObject* cls) -_register('PyObject_IsSubclass', ctypes.c_int, (ctypes.py_object,ctypes.py_object,)) -# int PyObject_IsTrue(PyObject* o) -_register('PyObject_IsTrue', ctypes.c_int, (ctypes.py_object,)) -# Py_ssize_t PyObject_Length(PyObject* o) -_register('PyObject_Length', ctypes.c_ssize_t, (ctypes.py_object,)) -# void* PyObject_Malloc(size_t n) -_register('PyObject_Malloc', ctypes.c_void_p, (ctypes.c_size_t,)) -# int PyObject_Not(PyObject* o) -_register('PyObject_Not', ctypes.c_int, (ctypes.py_object,)) -# void* PyObject_Realloc(void* p, size_t n) -_register('PyObject_Realloc', ctypes.c_void_p, (ctypes.c_void_p,ctypes.c_size_t,)) -# PyObject* PyObject_Repr(PyObject* o) -_register('PyObject_Repr', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyObject_RichCompare(PyObject* o1, PyObject* o2, int opid) -_register('PyObject_RichCompare', ctypes.py_object, (ctypes.py_object,ctypes.py_object,ctypes.c_int,)) -# int PyObject_RichCompareBool(PyObject* o1, PyObject* o2, int opid) -_register('PyObject_RichCompareBool', ctypes.c_int, (ctypes.py_object,ctypes.py_object,ctypes.c_int,)) -# int PyObject_SetAttr(PyObject* o, PyObject* attr_name, PyObject* v) -_register('PyObject_SetAttr', ctypes.c_int, (ctypes.py_object,ctypes.py_object,ctypes.py_object,)) -# int PyObject_SetAttrString(PyObject* o, const char* attr_name, PyObject* v) -_register('PyObject_SetAttrString', ctypes.c_int, (ctypes.py_object,ctypes.c_char_p,ctypes.py_object,)) -# int PyObject_SetItem(PyObject* o, PyObject* key, PyObject* v) -_register('PyObject_SetItem', ctypes.c_int, (ctypes.py_object,ctypes.py_object,ctypes.py_object,)) -# Py_ssize_t PyObject_Size(PyObject* o) -_register('PyObject_Size', ctypes.c_ssize_t, (ctypes.py_object,)) -# PyObject* PyObject_Str(PyObject* o) -_register('PyObject_Str', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyObject_Type(PyObject* o) -_register('PyObject_Type', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PySeqIter_New(PyObject* seq) -_register('PySeqIter_New', ctypes.py_object, (ctypes.py_object,)) -# int PySequence_Check(PyObject* o) -_register('PySequence_Check', ctypes.c_int, (ctypes.py_object,)) -# PyObject* PySequence_Concat(PyObject* o1, PyObject* o2) -_register('PySequence_Concat', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# int PySequence_Contains(PyObject* o, PyObject* value) -_register('PySequence_Contains', ctypes.c_int, (ctypes.py_object,ctypes.py_object,)) -# Py_ssize_t PySequence_Count(PyObject* o, PyObject* value) -_register('PySequence_Count', ctypes.c_ssize_t, (ctypes.py_object,ctypes.py_object,)) -# int PySequence_DelItem(PyObject* o, Py_ssize_t i) -_register('PySequence_DelItem', ctypes.c_int, (ctypes.py_object,ctypes.c_ssize_t,)) -# int PySequence_DelSlice(PyObject* o, Py_ssize_t i1, Py_ssize_t i2) -_register('PySequence_DelSlice', ctypes.c_int, (ctypes.py_object,ctypes.c_ssize_t,ctypes.c_ssize_t,)) -# PyObject* PySequence_Fast(PyObject* o, const char* m) -_register('PySequence_Fast', ctypes.py_object, (ctypes.py_object,ctypes.c_char_p,)) -# PyObject* PySequence_GetItem(PyObject* o, Py_ssize_t i) -_register('PySequence_GetItem', ctypes.py_object, (ctypes.py_object,ctypes.c_ssize_t,)) -# PyObject* PySequence_GetSlice(PyObject* o, Py_ssize_t i1, Py_ssize_t i2) -_register('PySequence_GetSlice', ctypes.py_object, (ctypes.py_object,ctypes.c_ssize_t,ctypes.c_ssize_t,)) -# PyObject* PySequence_InPlaceConcat(PyObject* o1, PyObject* o2) -_register('PySequence_InPlaceConcat', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PySequence_InPlaceRepeat(PyObject* o, Py_ssize_t count) -_register('PySequence_InPlaceRepeat', ctypes.py_object, (ctypes.py_object,ctypes.c_ssize_t,)) -# Py_ssize_t PySequence_Index(PyObject* o, PyObject* value) -_register('PySequence_Index', ctypes.c_ssize_t, (ctypes.py_object,ctypes.py_object,)) -# Py_ssize_t PySequence_Length(PyObject* o) -_register('PySequence_Length', ctypes.c_ssize_t, (ctypes.py_object,)) -# PyObject* PySequence_List(PyObject* o) -_register('PySequence_List', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PySequence_Repeat(PyObject* o, Py_ssize_t count) -_register('PySequence_Repeat', ctypes.py_object, (ctypes.py_object,ctypes.c_ssize_t,)) -# int PySequence_SetItem(PyObject* o, Py_ssize_t i, PyObject* v) -_register('PySequence_SetItem', ctypes.c_int, (ctypes.py_object,ctypes.c_ssize_t,ctypes.py_object,)) -# int PySequence_SetSlice(PyObject* o, Py_ssize_t i1, Py_ssize_t i2, PyObject* v) -_register('PySequence_SetSlice', ctypes.c_int, (ctypes.py_object,ctypes.c_ssize_t,ctypes.c_ssize_t,ctypes.py_object,)) -# Py_ssize_t PySequence_Size(PyObject* o) -_register('PySequence_Size', ctypes.c_ssize_t, (ctypes.py_object,)) -# PyObject* PySequence_Tuple(PyObject* o) -_register('PySequence_Tuple', ctypes.py_object, (ctypes.py_object,)) -# int PySet_Add(PyObject* set, PyObject* key) -_register('PySet_Add', ctypes.c_int, (ctypes.py_object,ctypes.py_object,)) -# int PySet_Clear(PyObject* set) -_register('PySet_Clear', ctypes.c_int, (ctypes.py_object,)) -# int PySet_Contains(PyObject* anyset, PyObject* key) -_register('PySet_Contains', ctypes.c_int, (ctypes.py_object,ctypes.py_object,)) -# int PySet_Discard(PyObject* set, PyObject* key) -_register('PySet_Discard', ctypes.c_int, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PySet_New(PyObject* iterable) -_register('PySet_New', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PySet_Pop(PyObject* set) -_register('PySet_Pop', ctypes.py_object, (ctypes.py_object,)) -# Py_ssize_t PySet_Size(PyObject* anyset) -_register('PySet_Size', ctypes.c_ssize_t, (ctypes.py_object,)) -# Py_ssize_t PySlice_AdjustIndices(Py_ssize_t length, Py_ssize_t* start, Py_ssize_t* stop, Py_ssize_t step) -_register('PySlice_AdjustIndices', ctypes.c_ssize_t, (ctypes.c_ssize_t,ctypes.POINTER(ctypes.c_ssize_t),ctypes.POINTER(ctypes.c_ssize_t),ctypes.c_ssize_t,), minver="3.6.1",) -# int PySlice_GetIndices(PyObject* slice, Py_ssize_t length, Py_ssize_t* start, Py_ssize_t* stop, Py_ssize_t* step) -_register('PySlice_GetIndices', ctypes.c_int, (ctypes.py_object,ctypes.c_ssize_t,ctypes.POINTER(ctypes.c_ssize_t),ctypes.POINTER(ctypes.c_ssize_t),ctypes.POINTER(ctypes.c_ssize_t),)) -# int PySlice_GetIndicesEx(PyObject* slice, Py_ssize_t length, Py_ssize_t* start, Py_ssize_t* stop, Py_ssize_t* step, Py_ssize_t* slicelength) -_register('PySlice_GetIndicesEx', ctypes.c_int, (ctypes.py_object,ctypes.c_ssize_t,ctypes.POINTER(ctypes.c_ssize_t),ctypes.POINTER(ctypes.c_ssize_t),ctypes.POINTER(ctypes.c_ssize_t),ctypes.POINTER(ctypes.c_ssize_t),)) -# PyObject* PySlice_New(PyObject* start, PyObject* stop, PyObject* step) -_register('PySlice_New', ctypes.py_object, (ctypes.py_object,ctypes.py_object,ctypes.py_object,)) -# int PySlice_Unpack(PyObject* slice, Py_ssize_t* start, Py_ssize_t* stop, Py_ssize_t* step) -_register('PySlice_Unpack', ctypes.c_int, (ctypes.py_object,ctypes.POINTER(ctypes.c_ssize_t),ctypes.POINTER(ctypes.c_ssize_t),ctypes.POINTER(ctypes.c_ssize_t),), minver="3.6.1",) -# int PyState_AddModule(PyObject* module, PyModuleDef* def) -_register('PyState_AddModule', ctypes.c_int, (ctypes.py_object,ctypes.POINTER(PyModuleDef),), minver="3.3",) -# PyObject* PyState_FindModule(PyModuleDef* def) -_register('PyState_FindModule', ctypes.py_object, (ctypes.POINTER(PyModuleDef),)) -# int PyState_RemoveModule(PyModuleDef* def) -_register('PyState_RemoveModule', ctypes.c_int, (ctypes.POINTER(PyModuleDef),), minver="3.3",) -# PyObject* PyStructSequence_GetItem(PyObject* p, Py_ssize_t pos) -_register('PyStructSequence_GetItem', ctypes.py_object, (ctypes.py_object,ctypes.c_ssize_t,)) -# PyObject* PyStructSequence_New(PyTypeObject* type) -_register('PyStructSequence_New', ctypes.py_object, (ctypes.POINTER(PyTypeObject),)) -# PyTypeObject* PyStructSequence_NewType(PyStructSequence_Desc* desc) -_register('PyStructSequence_NewType', ctypes.POINTER(PyTypeObject), ()) -# void PyStructSequence_SetItem(PyObject* p, Py_ssize_t pos, PyObject* o) -_register('PyStructSequence_SetItem', None, (ctypes.py_object,ctypes.c_ssize_t,ctypes.py_object,)) -# void PySys_AddWarnOption(const wchar_t* s) -_register('PySys_AddWarnOption', None, (ctypes.c_wchar_p,)) -# void PySys_AddWarnOptionUnicode(PyObject* unicode) -_register('PySys_AddWarnOptionUnicode', None, (ctypes.py_object,)) -# void PySys_AddXOption(const wchar_t* s) -_register('PySys_AddXOption', None, (ctypes.c_wchar_p,), minver="3.2",) -# void PySys_FormatStderr(const char* format, ...) -_register('PySys_FormatStderr', None, minver="3.2",) -# void PySys_FormatStdout(const char* format, ...) -_register('PySys_FormatStdout', None, minver="3.2",) -# PyObject* PySys_GetObject(const char* name) -_register('PySys_GetObject', ctypes.py_object, (ctypes.c_char_p,)) -# PyObject* PySys_GetXOptions() -_register('PySys_GetXOptions', ctypes.py_object, (), minver="3.2",) -# void PySys_ResetWarnOptions() -_register('PySys_ResetWarnOptions', None, ()) -# void PySys_SetArgv(int argc, wchar_t** argv) -_register('PySys_SetArgv', None, (ctypes.c_int,ctypes.POINTER(ctypes.c_wchar_p),)) -# void PySys_SetArgvEx(int argc, wchar_t** argv, int updatepath) -_register('PySys_SetArgvEx', None, (ctypes.c_int,ctypes.POINTER(ctypes.c_wchar_p),ctypes.c_int,), minver="3.1.3",) -# int PySys_SetObject(const char* name, PyObject* v) -_register('PySys_SetObject', ctypes.c_int, (ctypes.c_char_p,ctypes.py_object,)) -# void PySys_SetPath(const wchar_t* path) -_register('PySys_SetPath', None, (ctypes.c_wchar_p,)) -# void PySys_WriteStderr(const char* format, ...) -_register('PySys_WriteStderr', None) -# void PySys_WriteStdout(const char* format, ...) -_register('PySys_WriteStdout', None) -# void PyThreadState_Clear(PyThreadState* tstate) -_register('PyThreadState_Clear', None, (ctypes.POINTER(PyThreadState),)) -# void PyThreadState_Delete(PyThreadState* tstate) -_register('PyThreadState_Delete', None, (ctypes.POINTER(PyThreadState),)) -# PyThreadState* PyThreadState_Get() -_register('PyThreadState_Get', ctypes.POINTER(PyThreadState), ()) -# PyObject* PyThreadState_GetDict() -_register('PyThreadState_GetDict', ctypes.py_object, ()) -# PyFrameObject* PyThreadState_GetFrame(PyThreadState* tstate) -_register('PyThreadState_GetFrame', ctypes.POINTER(PyFrameObject), (ctypes.POINTER(PyThreadState),), minver="3.9",) -# uint64_t PyThreadState_GetID(PyThreadState* tstate) -_register('PyThreadState_GetID', ctypes.c_uint64, (ctypes.POINTER(PyThreadState),), minver="3.9",) -# PyInterpreterState* PyThreadState_GetInterpreter(PyThreadState* tstate) -_register('PyThreadState_GetInterpreter', ctypes.POINTER(PyInterpreterState), (ctypes.POINTER(PyThreadState),), minver="3.9",) -# PyThreadState* PyThreadState_New(PyInterpreterState* interp) -_register('PyThreadState_New', ctypes.POINTER(PyThreadState), (ctypes.POINTER(PyInterpreterState),)) -# int PyThreadState_SetAsyncExc(unsigned long id, PyObject* exc) -_register('PyThreadState_SetAsyncExc', ctypes.c_int, (ctypes.c_ulong,ctypes.py_object,)) -# PyThreadState* PyThreadState_Swap(PyThreadState* tstate) -_register('PyThreadState_Swap', ctypes.POINTER(PyThreadState), (ctypes.POINTER(PyThreadState),)) -# void PyThread_ReInitTLS() -_register('PyThread_ReInitTLS', None, ()) -# int PyThread_create_key() -_register('PyThread_create_key', ctypes.c_int, ()) -# void PyThread_delete_key(int key) -_register('PyThread_delete_key', None, (ctypes.c_int,)) -# void PyThread_delete_key_value(int key) -_register('PyThread_delete_key_value', None, (ctypes.c_int,)) -# void* PyThread_get_key_value(int key) -_register('PyThread_get_key_value', ctypes.c_void_p, (ctypes.c_int,)) -# int PyThread_set_key_value(int key, void* value) -_register('PyThread_set_key_value', ctypes.c_int, (ctypes.c_int,ctypes.c_void_p,)) -# Py_tss_t* PyThread_tss_alloc() -_register('PyThread_tss_alloc', ctypes.POINTER(Py_tss_t), ()) -# int PyThread_tss_create(Py_tss_t* key) -_register('PyThread_tss_create', ctypes.c_int, (ctypes.POINTER(Py_tss_t),)) -# void PyThread_tss_delete(Py_tss_t* key) -_register('PyThread_tss_delete', None, (ctypes.POINTER(Py_tss_t),)) -# void PyThread_tss_free(Py_tss_t* key) -_register('PyThread_tss_free', None, (ctypes.POINTER(Py_tss_t),)) -# void* PyThread_tss_get(Py_tss_t* key) -_register('PyThread_tss_get', ctypes.c_void_p, (ctypes.POINTER(Py_tss_t),)) -# int PyThread_tss_is_created(Py_tss_t* key) -_register('PyThread_tss_is_created', ctypes.c_int, (ctypes.POINTER(Py_tss_t),)) -# int PyThread_tss_set(Py_tss_t* key, void* value) -_register('PyThread_tss_set', ctypes.c_int, (ctypes.POINTER(Py_tss_t),ctypes.c_void_p,)) -# PyObject* PyTuple_GetItem(PyObject* p, Py_ssize_t pos) -_register('PyTuple_GetItem', ctypes.py_object, (ctypes.py_object,ctypes.c_ssize_t,)) -# PyObject* PyTuple_GetSlice(PyObject* p, Py_ssize_t low, Py_ssize_t high) -_register('PyTuple_GetSlice', ctypes.py_object, (ctypes.py_object,ctypes.c_ssize_t,ctypes.c_ssize_t,)) -# PyObject* PyTuple_New(Py_ssize_t len) -_register('PyTuple_New', ctypes.py_object, (ctypes.c_ssize_t,)) -# PyObject* PyTuple_Pack(Py_ssize_t n, ...) -_register('PyTuple_Pack', ctypes.py_object) -# int PyTuple_SetItem(PyObject* p, Py_ssize_t pos, PyObject* o) -_register('PyTuple_SetItem', ctypes.c_int, (ctypes.py_object,ctypes.c_ssize_t,ctypes.py_object,)) -# Py_ssize_t PyTuple_Size(PyObject* p) -_register('PyTuple_Size', ctypes.c_ssize_t, (ctypes.py_object,)) -# unsigned int PyType_ClearCache() -_register('PyType_ClearCache', ctypes.c_uint, ()) -# PyObject* PyType_FromModuleAndSpec(PyObject* module, PyType_Spec* spec, PyObject* bases) -_register('PyType_FromModuleAndSpec', ctypes.py_object, (ctypes.py_object,ctypes.POINTER(PyType_Spec),ctypes.py_object,), minver="3.9",) -# PyObject* PyType_FromSpec(PyType_Spec* spec) -_register('PyType_FromSpec', ctypes.py_object, (ctypes.POINTER(PyType_Spec),)) -# PyObject* PyType_FromSpecWithBases(PyType_Spec* spec, PyObject* bases) -_register('PyType_FromSpecWithBases', ctypes.py_object, (ctypes.POINTER(PyType_Spec),ctypes.py_object,), minver="3.3",) -# PyObject* PyType_GenericAlloc(PyTypeObject* type, Py_ssize_t nitems) -_register('PyType_GenericAlloc', ctypes.py_object, (ctypes.POINTER(PyTypeObject),ctypes.c_ssize_t,)) -# PyObject* PyType_GenericNew(PyTypeObject* type, PyObject* args, PyObject* kwds) -_register('PyType_GenericNew', ctypes.py_object, (ctypes.POINTER(PyTypeObject),ctypes.py_object,ctypes.py_object,)) -# unsigned long PyType_GetFlags(PyTypeObject* type) -_register('PyType_GetFlags', ctypes.c_ulong, (ctypes.POINTER(PyTypeObject),), minver="3.2",) -# PyObject* PyType_GetModule(PyTypeObject* type) -_register('PyType_GetModule', ctypes.py_object, (ctypes.POINTER(PyTypeObject),), minver="3.9",) -# void* PyType_GetModuleState(PyTypeObject* type) -_register('PyType_GetModuleState', ctypes.c_void_p, (ctypes.POINTER(PyTypeObject),), minver="3.9",) -# PyObject* PyType_GetName(PyTypeObject* type) -_register('PyType_GetName', ctypes.py_object, (ctypes.POINTER(PyTypeObject),), minver="3.11",) -# PyObject* PyType_GetQualName(PyTypeObject* type) -_register('PyType_GetQualName', ctypes.py_object, (ctypes.POINTER(PyTypeObject),), minver="3.11",) -# void* PyType_GetSlot(PyTypeObject* type, int slot) -_register('PyType_GetSlot', ctypes.c_void_p, (ctypes.POINTER(PyTypeObject),ctypes.c_int,), minver="3.4",) -# int PyType_IsSubtype(PyTypeObject* a, PyTypeObject* b) -_register('PyType_IsSubtype', ctypes.c_int, (ctypes.POINTER(PyTypeObject),ctypes.POINTER(PyTypeObject),)) -# void PyType_Modified(PyTypeObject* type) -_register('PyType_Modified', None, (ctypes.POINTER(PyTypeObject),)) -# int PyType_Ready(PyTypeObject* type) -_register('PyType_Ready', ctypes.c_int, (ctypes.POINTER(PyTypeObject),)) -# PyObject* PyUnicodeDecodeError_Create(const char* encoding, const char* object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char* reason) -_register('PyUnicodeDecodeError_Create', ctypes.py_object, (ctypes.c_char_p,ctypes.c_char_p,ctypes.c_ssize_t,ctypes.c_ssize_t,ctypes.c_ssize_t,ctypes.c_char_p,)) -# PyObject* PyUnicodeDecodeError_GetEncoding(PyObject* exc) -_register('PyUnicodeDecodeError_GetEncoding', ctypes.py_object, (ctypes.py_object,)) -# int PyUnicodeDecodeError_GetEnd(PyObject* exc, Py_ssize_t* end) -_register('PyUnicodeDecodeError_GetEnd', ctypes.c_int, (ctypes.py_object,ctypes.POINTER(ctypes.c_ssize_t),)) -# PyObject* PyUnicodeDecodeError_GetObject(PyObject* exc) -_register('PyUnicodeDecodeError_GetObject', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyUnicodeDecodeError_GetReason(PyObject* exc) -_register('PyUnicodeDecodeError_GetReason', ctypes.py_object, (ctypes.py_object,)) -# int PyUnicodeDecodeError_GetStart(PyObject* exc, Py_ssize_t* start) -_register('PyUnicodeDecodeError_GetStart', ctypes.c_int, (ctypes.py_object,ctypes.POINTER(ctypes.c_ssize_t),)) -# int PyUnicodeDecodeError_SetEnd(PyObject* exc, Py_ssize_t end) -_register('PyUnicodeDecodeError_SetEnd', ctypes.c_int, (ctypes.py_object,ctypes.c_ssize_t,)) -# int PyUnicodeDecodeError_SetReason(PyObject* exc, const char* reason) -_register('PyUnicodeDecodeError_SetReason', ctypes.c_int, (ctypes.py_object,ctypes.c_char_p,)) -# int PyUnicodeDecodeError_SetStart(PyObject* exc, Py_ssize_t start) -_register('PyUnicodeDecodeError_SetStart', ctypes.c_int, (ctypes.py_object,ctypes.c_ssize_t,)) -# PyObject* PyUnicodeEncodeError_GetEncoding(PyObject* exc) -_register('PyUnicodeEncodeError_GetEncoding', ctypes.py_object, (ctypes.py_object,)) -# int PyUnicodeEncodeError_GetEnd(PyObject* exc, Py_ssize_t* end) -_register('PyUnicodeEncodeError_GetEnd', ctypes.c_int, (ctypes.py_object,ctypes.POINTER(ctypes.c_ssize_t),)) -# PyObject* PyUnicodeEncodeError_GetObject(PyObject* exc) -_register('PyUnicodeEncodeError_GetObject', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyUnicodeEncodeError_GetReason(PyObject* exc) -_register('PyUnicodeEncodeError_GetReason', ctypes.py_object, (ctypes.py_object,)) -# int PyUnicodeEncodeError_GetStart(PyObject* exc, Py_ssize_t* start) -_register('PyUnicodeEncodeError_GetStart', ctypes.c_int, (ctypes.py_object,ctypes.POINTER(ctypes.c_ssize_t),)) -# int PyUnicodeEncodeError_SetEnd(PyObject* exc, Py_ssize_t end) -_register('PyUnicodeEncodeError_SetEnd', ctypes.c_int, (ctypes.py_object,ctypes.c_ssize_t,)) -# int PyUnicodeEncodeError_SetReason(PyObject* exc, const char* reason) -_register('PyUnicodeEncodeError_SetReason', ctypes.c_int, (ctypes.py_object,ctypes.c_char_p,)) -# int PyUnicodeEncodeError_SetStart(PyObject* exc, Py_ssize_t start) -_register('PyUnicodeEncodeError_SetStart', ctypes.c_int, (ctypes.py_object,ctypes.c_ssize_t,)) -# int PyUnicodeTranslateError_GetEnd(PyObject* exc, Py_ssize_t* end) -_register('PyUnicodeTranslateError_GetEnd', ctypes.c_int, (ctypes.py_object,ctypes.POINTER(ctypes.c_ssize_t),)) -# PyObject* PyUnicodeTranslateError_GetObject(PyObject* exc) -_register('PyUnicodeTranslateError_GetObject', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyUnicodeTranslateError_GetReason(PyObject* exc) -_register('PyUnicodeTranslateError_GetReason', ctypes.py_object, (ctypes.py_object,)) -# int PyUnicodeTranslateError_GetStart(PyObject* exc, Py_ssize_t* start) -_register('PyUnicodeTranslateError_GetStart', ctypes.c_int, (ctypes.py_object,ctypes.POINTER(ctypes.c_ssize_t),)) -# int PyUnicodeTranslateError_SetEnd(PyObject* exc, Py_ssize_t end) -_register('PyUnicodeTranslateError_SetEnd', ctypes.c_int, (ctypes.py_object,ctypes.c_ssize_t,)) -# int PyUnicodeTranslateError_SetReason(PyObject* exc, const char* reason) -_register('PyUnicodeTranslateError_SetReason', ctypes.c_int, (ctypes.py_object,ctypes.c_char_p,)) -# int PyUnicodeTranslateError_SetStart(PyObject* exc, Py_ssize_t start) -_register('PyUnicodeTranslateError_SetStart', ctypes.c_int, (ctypes.py_object,ctypes.c_ssize_t,)) -# PyObject* PyUnicode_AsASCIIString(PyObject* unicode) -_register('PyUnicode_AsASCIIString', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyUnicode_AsCharmapString(PyObject* unicode, PyObject* mapping) -_register('PyUnicode_AsCharmapString', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyUnicode_AsEncodedString(PyObject* unicode, const char* encoding, const char* errors) -_register('PyUnicode_AsEncodedString', ctypes.py_object, (ctypes.py_object,ctypes.c_char_p,ctypes.c_char_p,)) -# PyObject* PyUnicode_AsLatin1String(PyObject* unicode) -_register('PyUnicode_AsLatin1String', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyUnicode_AsMBCSString(PyObject* unicode) -_register('PyUnicode_AsMBCSString', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyUnicode_AsRawUnicodeEscapeString(PyObject* unicode) -_register('PyUnicode_AsRawUnicodeEscapeString', ctypes.py_object, (ctypes.py_object,)) -# Py_UCS4* PyUnicode_AsUCS4(PyObject* unicode, Py_UCS4* buffer, Py_ssize_t buflen, int copy_null) -_register('PyUnicode_AsUCS4', ctypes.POINTER(Py_UCS4), (ctypes.py_object,ctypes.POINTER(Py_UCS4),ctypes.c_ssize_t,ctypes.c_int,), minver="3.3",) -# Py_UCS4* PyUnicode_AsUCS4Copy(PyObject* unicode) -_register('PyUnicode_AsUCS4Copy', ctypes.POINTER(Py_UCS4), (ctypes.py_object,), minver="3.3",) -# PyObject* PyUnicode_AsUTF16String(PyObject* unicode) -_register('PyUnicode_AsUTF16String', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyUnicode_AsUTF32String(PyObject* unicode) -_register('PyUnicode_AsUTF32String', ctypes.py_object, (ctypes.py_object,)) -# const char* PyUnicode_AsUTF8AndSize(PyObject* unicode, Py_ssize_t* size) -_register('PyUnicode_AsUTF8AndSize', ctypes.c_char_p, (ctypes.py_object,ctypes.POINTER(ctypes.c_ssize_t),), minver="3.3",) -# PyObject* PyUnicode_AsUTF8String(PyObject* unicode) -_register('PyUnicode_AsUTF8String', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyUnicode_AsUnicodeEscapeString(PyObject* unicode) -_register('PyUnicode_AsUnicodeEscapeString', ctypes.py_object, (ctypes.py_object,)) -# Py_ssize_t PyUnicode_AsWideChar(PyObject* unicode, wchar_t* wstr, Py_ssize_t size) -_register('PyUnicode_AsWideChar', ctypes.c_ssize_t, (ctypes.py_object,ctypes.c_wchar_p,ctypes.c_ssize_t,)) -# wchar_t* PyUnicode_AsWideCharString(PyObject* unicode, Py_ssize_t* size) -_register('PyUnicode_AsWideCharString', ctypes.c_wchar_p, (ctypes.py_object,ctypes.POINTER(ctypes.c_ssize_t),), minver="3.2",) -# int PyUnicode_Compare(PyObject* left, PyObject* right) -_register('PyUnicode_Compare', ctypes.c_int, (ctypes.py_object,ctypes.py_object,)) -# int PyUnicode_CompareWithASCIIString(PyObject* unicode, const char* string) -_register('PyUnicode_CompareWithASCIIString', ctypes.c_int, (ctypes.py_object,ctypes.c_char_p,)) -# PyObject* PyUnicode_Concat(PyObject* left, PyObject* right) -_register('PyUnicode_Concat', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# int PyUnicode_Contains(PyObject* unicode, PyObject* substr) -_register('PyUnicode_Contains', ctypes.c_int, (ctypes.py_object,ctypes.py_object,)) -# Py_ssize_t PyUnicode_Count(PyObject* unicode, PyObject* substr, Py_ssize_t start, Py_ssize_t end) -_register('PyUnicode_Count', ctypes.c_ssize_t, (ctypes.py_object,ctypes.py_object,ctypes.c_ssize_t,ctypes.c_ssize_t,)) -# PyObject* PyUnicode_Decode(const char* str, Py_ssize_t size, const char* encoding, const char* errors) -_register('PyUnicode_Decode', ctypes.py_object, (ctypes.c_char_p,ctypes.c_ssize_t,ctypes.c_char_p,ctypes.c_char_p,)) -# PyObject* PyUnicode_DecodeASCII(const char* str, Py_ssize_t size, const char* errors) -_register('PyUnicode_DecodeASCII', ctypes.py_object, (ctypes.c_char_p,ctypes.c_ssize_t,ctypes.c_char_p,)) -# PyObject* PyUnicode_DecodeCharmap(const char* str, Py_ssize_t length, PyObject* mapping, const char* errors) -_register('PyUnicode_DecodeCharmap', ctypes.py_object, (ctypes.c_char_p,ctypes.c_ssize_t,ctypes.py_object,ctypes.c_char_p,)) -# PyObject* PyUnicode_DecodeFSDefault(const char* str) -_register('PyUnicode_DecodeFSDefault', ctypes.py_object, (ctypes.c_char_p,)) -# PyObject* PyUnicode_DecodeFSDefaultAndSize(const char* str, Py_ssize_t size) -_register('PyUnicode_DecodeFSDefaultAndSize', ctypes.py_object, (ctypes.c_char_p,ctypes.c_ssize_t,)) -# PyObject* PyUnicode_DecodeLatin1(const char* str, Py_ssize_t size, const char* errors) -_register('PyUnicode_DecodeLatin1', ctypes.py_object, (ctypes.c_char_p,ctypes.c_ssize_t,ctypes.c_char_p,)) -# PyObject* PyUnicode_DecodeLocale(const char* str, const char* errors) -_register('PyUnicode_DecodeLocale', ctypes.py_object, (ctypes.c_char_p,ctypes.c_char_p,), minver="3.3",) -# PyObject* PyUnicode_DecodeLocaleAndSize(const char* str, Py_ssize_t length, const char* errors) -_register('PyUnicode_DecodeLocaleAndSize', ctypes.py_object, (ctypes.c_char_p,ctypes.c_ssize_t,ctypes.c_char_p,), minver="3.3",) -# PyObject* PyUnicode_DecodeMBCS(const char* str, Py_ssize_t size, const char* errors) -_register('PyUnicode_DecodeMBCS', ctypes.py_object, (ctypes.c_char_p,ctypes.c_ssize_t,ctypes.c_char_p,)) -# PyObject* PyUnicode_DecodeMBCSStateful(const char* str, Py_ssize_t size, const char* errors, Py_ssize_t* consumed) -_register('PyUnicode_DecodeMBCSStateful', ctypes.py_object, (ctypes.c_char_p,ctypes.c_ssize_t,ctypes.c_char_p,ctypes.POINTER(ctypes.c_ssize_t),)) -# PyObject* PyUnicode_DecodeRawUnicodeEscape(const char* str, Py_ssize_t size, const char* errors) -_register('PyUnicode_DecodeRawUnicodeEscape', ctypes.py_object, (ctypes.c_char_p,ctypes.c_ssize_t,ctypes.c_char_p,)) -# PyObject* PyUnicode_DecodeUTF16(const char* str, Py_ssize_t size, const char* errors, int* byteorder) -_register('PyUnicode_DecodeUTF16', ctypes.py_object, (ctypes.c_char_p,ctypes.c_ssize_t,ctypes.c_char_p,ctypes.POINTER(ctypes.c_int),)) -# PyObject* PyUnicode_DecodeUTF16Stateful(const char* str, Py_ssize_t size, const char* errors, int* byteorder, Py_ssize_t* consumed) -_register('PyUnicode_DecodeUTF16Stateful', ctypes.py_object, (ctypes.c_char_p,ctypes.c_ssize_t,ctypes.c_char_p,ctypes.POINTER(ctypes.c_int),ctypes.POINTER(ctypes.c_ssize_t),)) -# PyObject* PyUnicode_DecodeUTF32(const char* str, Py_ssize_t size, const char* errors, int* byteorder) -_register('PyUnicode_DecodeUTF32', ctypes.py_object, (ctypes.c_char_p,ctypes.c_ssize_t,ctypes.c_char_p,ctypes.POINTER(ctypes.c_int),)) -# PyObject* PyUnicode_DecodeUTF32Stateful(const char* str, Py_ssize_t size, const char* errors, int* byteorder, Py_ssize_t* consumed) -_register('PyUnicode_DecodeUTF32Stateful', ctypes.py_object, (ctypes.c_char_p,ctypes.c_ssize_t,ctypes.c_char_p,ctypes.POINTER(ctypes.c_int),ctypes.POINTER(ctypes.c_ssize_t),)) -# PyObject* PyUnicode_DecodeUTF7(const char* str, Py_ssize_t size, const char* errors) -_register('PyUnicode_DecodeUTF7', ctypes.py_object, (ctypes.c_char_p,ctypes.c_ssize_t,ctypes.c_char_p,)) -# PyObject* PyUnicode_DecodeUTF7Stateful(const char* str, Py_ssize_t size, const char* errors, Py_ssize_t* consumed) -_register('PyUnicode_DecodeUTF7Stateful', ctypes.py_object, (ctypes.c_char_p,ctypes.c_ssize_t,ctypes.c_char_p,ctypes.POINTER(ctypes.c_ssize_t),)) -# PyObject* PyUnicode_DecodeUTF8(const char* str, Py_ssize_t size, const char* errors) -_register('PyUnicode_DecodeUTF8', ctypes.py_object, (ctypes.c_char_p,ctypes.c_ssize_t,ctypes.c_char_p,)) -# PyObject* PyUnicode_DecodeUTF8Stateful(const char* str, Py_ssize_t size, const char* errors, Py_ssize_t* consumed) -_register('PyUnicode_DecodeUTF8Stateful', ctypes.py_object, (ctypes.c_char_p,ctypes.c_ssize_t,ctypes.c_char_p,ctypes.POINTER(ctypes.c_ssize_t),)) -# PyObject* PyUnicode_DecodeUnicodeEscape(const char* str, Py_ssize_t size, const char* errors) -_register('PyUnicode_DecodeUnicodeEscape', ctypes.py_object, (ctypes.c_char_p,ctypes.c_ssize_t,ctypes.c_char_p,)) -# PyObject* PyUnicode_EncodeCodePage(int code_page, PyObject* unicode, const char* errors) -_register('PyUnicode_EncodeCodePage', ctypes.py_object, (ctypes.c_int,ctypes.py_object,ctypes.c_char_p,), minver="3.3",) -# PyObject* PyUnicode_EncodeFSDefault(PyObject* unicode) -_register('PyUnicode_EncodeFSDefault', ctypes.py_object, (ctypes.py_object,), minver="3.2",) -# PyObject* PyUnicode_EncodeLocale(PyObject* unicode, const char* errors) -_register('PyUnicode_EncodeLocale', ctypes.py_object, (ctypes.py_object,ctypes.c_char_p,), minver="3.3",) -# int PyUnicode_FSConverter(PyObject* obj, void* result) -_register('PyUnicode_FSConverter', ctypes.c_int, (ctypes.py_object,ctypes.c_void_p,), minver="3.1",) -# int PyUnicode_FSDecoder(PyObject* obj, void* result) -_register('PyUnicode_FSDecoder', ctypes.c_int, (ctypes.py_object,ctypes.c_void_p,), minver="3.2",) -# Py_ssize_t PyUnicode_Find(PyObject* unicode, PyObject* substr, Py_ssize_t start, Py_ssize_t end, int direction) -_register('PyUnicode_Find', ctypes.c_ssize_t, (ctypes.py_object,ctypes.py_object,ctypes.c_ssize_t,ctypes.c_ssize_t,ctypes.c_int,)) -# Py_ssize_t PyUnicode_FindChar(PyObject* unicode, Py_UCS4 ch, Py_ssize_t start, Py_ssize_t end, int direction) -_register('PyUnicode_FindChar', ctypes.c_ssize_t, (ctypes.py_object,Py_UCS4,ctypes.c_ssize_t,ctypes.c_ssize_t,ctypes.c_int,), minver="3.3",) -# PyObject* PyUnicode_Format(PyObject* format, PyObject* args) -_register('PyUnicode_Format', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyUnicode_FromEncodedObject(PyObject* obj, const char* encoding, const char* errors) -_register('PyUnicode_FromEncodedObject', ctypes.py_object, (ctypes.py_object,ctypes.c_char_p,ctypes.c_char_p,)) -# PyObject* PyUnicode_FromFormat(const char* format, ...) -_register('PyUnicode_FromFormat', ctypes.py_object) -# PyObject* PyUnicode_FromFormatV(const char* format, va_list vargs) -_register('PyUnicode_FromFormatV', ctypes.py_object, (ctypes.c_char_p,ctypes.c_void_p,)) -# PyObject* PyUnicode_FromObject(PyObject* obj) -_register('PyUnicode_FromObject', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyUnicode_FromString(const char* str) -_register('PyUnicode_FromString', ctypes.py_object, (ctypes.c_char_p,)) -# PyObject* PyUnicode_FromStringAndSize(const char* str, Py_ssize_t size) -_register('PyUnicode_FromStringAndSize', ctypes.py_object, (ctypes.c_char_p,ctypes.c_ssize_t,)) -# PyObject* PyUnicode_FromWideChar(const wchar_t* wstr, Py_ssize_t size) -_register('PyUnicode_FromWideChar', ctypes.py_object, (ctypes.c_wchar_p,ctypes.c_ssize_t,)) -# Py_ssize_t PyUnicode_GetLength(PyObject* unicode) -_register('PyUnicode_GetLength', ctypes.c_ssize_t, (ctypes.py_object,), minver="3.3",) -# Py_ssize_t PyUnicode_GetSize(PyObject* unicode) -_register('PyUnicode_GetSize', ctypes.c_ssize_t, (ctypes.py_object,)) -# PyObject* PyUnicode_InternFromString(const char* str) -_register('PyUnicode_InternFromString', ctypes.py_object, (ctypes.c_char_p,)) -# void PyUnicode_InternInPlace(PyObject** p_unicode) -_register('PyUnicode_InternInPlace', None, (ctypes.POINTER(ctypes.py_object),)) -# int PyUnicode_IsIdentifier(PyObject* unicode) -_register('PyUnicode_IsIdentifier', ctypes.c_int, (ctypes.py_object,)) -# PyObject* PyUnicode_Join(PyObject* separator, PyObject* seq) -_register('PyUnicode_Join', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# Py_UCS4 PyUnicode_ReadChar(PyObject* unicode, Py_ssize_t index) -_register('PyUnicode_ReadChar', Py_UCS4, (ctypes.py_object,ctypes.c_ssize_t,), minver="3.3",) -# PyObject* PyUnicode_Replace(PyObject* unicode, PyObject* substr, PyObject* replstr, Py_ssize_t maxcount) -_register('PyUnicode_Replace', ctypes.py_object, (ctypes.py_object,ctypes.py_object,ctypes.py_object,ctypes.c_ssize_t,)) -# PyObject* PyUnicode_RichCompare(PyObject* left, PyObject* right, int op) -_register('PyUnicode_RichCompare', ctypes.py_object, (ctypes.py_object,ctypes.py_object,ctypes.c_int,)) -# PyObject* PyUnicode_Split(PyObject* unicode, PyObject* sep, Py_ssize_t maxsplit) -_register('PyUnicode_Split', ctypes.py_object, (ctypes.py_object,ctypes.py_object,ctypes.c_ssize_t,)) -# PyObject* PyUnicode_Splitlines(PyObject* unicode, int keepends) -_register('PyUnicode_Splitlines', ctypes.py_object, (ctypes.py_object,ctypes.c_int,)) -# PyObject* PyUnicode_Substring(PyObject* unicode, Py_ssize_t start, Py_ssize_t end) -_register('PyUnicode_Substring', ctypes.py_object, (ctypes.py_object,ctypes.c_ssize_t,ctypes.c_ssize_t,), minver="3.3",) -# Py_ssize_t PyUnicode_Tailmatch(PyObject* unicode, PyObject* substr, Py_ssize_t start, Py_ssize_t end, int direction) -_register('PyUnicode_Tailmatch', ctypes.c_ssize_t, (ctypes.py_object,ctypes.py_object,ctypes.c_ssize_t,ctypes.c_ssize_t,ctypes.c_int,)) -# PyObject* PyUnicode_Translate(PyObject* unicode, PyObject* table, const char* errors) -_register('PyUnicode_Translate', ctypes.py_object, (ctypes.py_object,ctypes.py_object,ctypes.c_char_p,)) -# int PyUnicode_WriteChar(PyObject* unicode, Py_ssize_t index, Py_UCS4 character) -_register('PyUnicode_WriteChar', ctypes.c_int, (ctypes.py_object,ctypes.c_ssize_t,Py_UCS4,), minver="3.3",) -# PyObject* PyWeakref_GetObject(PyObject* ref) -_register('PyWeakref_GetObject', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyWeakref_NewProxy(PyObject* ob, PyObject* callback) -_register('PyWeakref_NewProxy', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# PyObject* PyWeakref_NewRef(PyObject* ob, PyObject* callback) -_register('PyWeakref_NewRef', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# int Py_AddPendingCall(int (*func)(void*), void* arg) -_register('Py_AddPendingCall', ctypes.c_int, (ctypes.c_int,ctypes.c_void_p,), minver="3.1",) -# PyObject* Py_BuildValue(const char* format, ...) -_register('Py_BuildValue', ctypes.py_object) -# int Py_BytesMain(int argc, char** argv) -_register('Py_BytesMain', ctypes.c_int, (ctypes.c_int,ctypes.POINTER(ctypes.c_char_p),), minver="3.8",) -# PyObject* Py_CompileString(const char* str, const char* filename, int start) -_register('Py_CompileString', ctypes.py_object, (ctypes.c_char_p,ctypes.c_char_p,ctypes.c_int,)) -# void Py_DecRef(PyObject* o) -_register('Py_DecRef', None, (ctypes.py_object,)) -# wchar_t* Py_DecodeLocale(const char* arg, size_t* size) -_register('Py_DecodeLocale', ctypes.c_wchar_p, (ctypes.c_char_p,ctypes.POINTER(ctypes.c_size_t),), minver="3.5",) -# char* Py_EncodeLocale(const wchar_t* text, size_t* error_pos) -_register('Py_EncodeLocale', ctypes.c_char_p, (ctypes.c_wchar_p,ctypes.POINTER(ctypes.c_size_t),), minver="3.5",) -# void Py_EndInterpreter(PyThreadState* tstate) -_register('Py_EndInterpreter', None, (ctypes.POINTER(PyThreadState),)) -# int Py_EnterRecursiveCall(const char* where) -_register('Py_EnterRecursiveCall', ctypes.c_int, (ctypes.c_char_p,)) -# void Py_Exit(int status) -_register('Py_Exit', None, (ctypes.c_int,)) -# void Py_FatalError(const char* message) -_register('Py_FatalError', None, (ctypes.c_char_p,)) -# void Py_Finalize() -_register('Py_Finalize', None, ()) -# int Py_FinalizeEx() -_register('Py_FinalizeEx', ctypes.c_int, (), minver="3.6",) -# PyObject* Py_GenericAlias(PyObject* origin, PyObject* args) -_register('Py_GenericAlias', ctypes.py_object, (ctypes.py_object,ctypes.py_object,), minver="3.9",) -# const char* Py_GetBuildInfo() -_register('Py_GetBuildInfo', ctypes.c_char_p, ()) -# const char* Py_GetCompiler() -_register('Py_GetCompiler', ctypes.c_char_p, ()) -# const char* Py_GetCopyright() -_register('Py_GetCopyright', ctypes.c_char_p, ()) -# wchar_t* Py_GetExecPrefix() -_register('Py_GetExecPrefix', ctypes.c_wchar_p, ()) -# wchar_t* Py_GetPath() -_register('Py_GetPath', ctypes.c_wchar_p, ()) -# const char* Py_GetPlatform() -_register('Py_GetPlatform', ctypes.c_char_p, ()) -# wchar_t* Py_GetPrefix() -_register('Py_GetPrefix', ctypes.c_wchar_p, ()) -# wchar_t* Py_GetProgramFullPath() -_register('Py_GetProgramFullPath', ctypes.c_wchar_p, ()) -# wchar_t* Py_GetProgramName() -_register('Py_GetProgramName', ctypes.c_wchar_p, ()) -# wchar_t* Py_GetPythonHome() -_register('Py_GetPythonHome', ctypes.c_wchar_p, ()) -# const char* Py_GetVersion() -_register('Py_GetVersion', ctypes.c_char_p, ()) -# void Py_IncRef(PyObject* o) -_register('Py_IncRef', None, (ctypes.py_object,)) -# void Py_Initialize() -_register('Py_Initialize', None, ()) -# void Py_InitializeEx(int initsigs) -_register('Py_InitializeEx', None, (ctypes.c_int,)) -# int Py_Is(PyObject* x, PyObject* y) -_register('Py_Is', ctypes.c_int, (ctypes.py_object,ctypes.py_object,), minver="3.10",) -# int Py_IsFalse(PyObject* x) -_register('Py_IsFalse', ctypes.c_int, (ctypes.py_object,), minver="3.10",) -# int Py_IsInitialized() -_register('Py_IsInitialized', ctypes.c_int, ()) -# int Py_IsNone(PyObject* x) -_register('Py_IsNone', ctypes.c_int, (ctypes.py_object,), minver="3.10",) -# int Py_IsTrue(PyObject* x) -_register('Py_IsTrue', ctypes.c_int, (ctypes.py_object,), minver="3.10",) -# void Py_LeaveRecursiveCall(void) -_register('Py_LeaveRecursiveCall', None, ()) -# int Py_Main(int argc, wchar_t** argv) -_register('Py_Main', ctypes.c_int, (ctypes.c_int,ctypes.POINTER(ctypes.c_wchar_p),)) -# PyThreadState* Py_NewInterpreter() -_register('Py_NewInterpreter', ctypes.POINTER(PyThreadState), ()) -# PyObject* Py_NewRef(PyObject* o) -_register('Py_NewRef', ctypes.py_object, (ctypes.py_object,), minver="3.10",) -# int Py_ReprEnter(PyObject* object) -_register('Py_ReprEnter', ctypes.c_int, (ctypes.py_object,)) -# void Py_ReprLeave(PyObject* object) -_register('Py_ReprLeave', None, (ctypes.py_object,)) -# void Py_SetProgramName(const wchar_t* name) -_register('Py_SetProgramName', None, (ctypes.c_wchar_p,)) -# void Py_SetPythonHome(const wchar_t* home) -_register('Py_SetPythonHome', None, (ctypes.c_wchar_p,)) -# PyObject* Py_VaBuildValue(const char* format, va_list vargs) -_register('Py_VaBuildValue', ctypes.py_object, (ctypes.c_char_p,ctypes.c_void_p,)) -# PyObject* Py_XNewRef(PyObject* o) -_register('Py_XNewRef', ctypes.py_object, (ctypes.py_object,), minver="3.10",) -# int PyOS_mystrnicmp(const char*, const char*, Py_ssize_t) -_register('PyOS_mystrnicmp', ctypes.c_int, ()) -# int PyOS_InterruptOccurred(void) -_register('PyOS_InterruptOccurred', ctypes.c_int, ()) -# PyObject* _PyLong_Rshift(PyObject*, size_t) -_register('_PyLong_Rshift', ctypes.py_object, ()) -# PyObject* _PyLong_Lshift(PyObject*, size_t) -_register('_PyLong_Lshift', ctypes.py_object, ()) -# int _PyFrame_IsEntryFrame(PyFrameObject* frame) -_register('_PyFrame_IsEntryFrame', ctypes.c_int, (ctypes.POINTER(PyFrameObject),)) -# int PyFrame_FastToLocalsWithError(PyFrameObject* f) -_register('PyFrame_FastToLocalsWithError', ctypes.c_int, (ctypes.POINTER(PyFrameObject),)) -# void _Py_NewReference(PyObject* op) -_register('_Py_NewReference', None, (ctypes.py_object,)) -# int _Py_CoerceLegacyLocale(int warn) -_register('_Py_CoerceLegacyLocale', ctypes.c_int, (ctypes.c_int,)) -# int _Py_LegacyLocaleDetected(int warn) -_register('_Py_LegacyLocaleDetected', ctypes.c_int, (ctypes.c_int,)) -# char* _Py_SetLocaleFromEnv(int category) -_register('_Py_SetLocaleFromEnv', ctypes.c_char_p, (ctypes.c_int,)) -# PyThreadState* _Py_NewInterpreter(int isolated_subinterpreter) -_register('_Py_NewInterpreter', ctypes.POINTER(PyThreadState), (ctypes.c_int,)) -# int PyCompile_OpcodeStackEffect(int opcode, int oparg) -_register('PyCompile_OpcodeStackEffect', ctypes.c_int, (ctypes.c_int,ctypes.c_int,)) -# int PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump) -_register('PyCompile_OpcodeStackEffectWithJump', ctypes.c_int, (ctypes.c_int,ctypes.c_int,ctypes.c_int,)) -# Py_ssize_t _PyWeakref_GetWeakrefCount(PyWeakReference* head) -_register('_PyWeakref_GetWeakrefCount', ctypes.c_ssize_t, ()) -# void _PyWeakref_ClearRef(PyWeakReference* self) -_register('_PyWeakref_ClearRef', None, ()) -# int _PySet_NextEntry(PyObject* set, Py_ssize_t* pos, PyObject** key, Py_hash_t* hash) -_register('_PySet_NextEntry', ctypes.c_int, (ctypes.py_object,ctypes.POINTER(ctypes.c_ssize_t),ctypes.POINTER(ctypes.py_object),ctypes.POINTER(ctypes.c_ssize_t),)) -# int _PySet_Update(PyObject* set, PyObject* iterable) -_register('_PySet_Update', ctypes.c_int, (ctypes.py_object,ctypes.py_object,)) -# void _PyTraceback_Add(const char*, const char*, int) -_register('_PyTraceback_Add', None, ()) -# PyObject* PyContext_New(void) -_register('PyContext_New', ctypes.py_object, ()) -# PyObject* PyContext_CopyCurrent(void) -_register('PyContext_CopyCurrent', ctypes.py_object, ()) -# PyObject* _PyImport_GetModuleId(_Py_Identifier* name) -_register('_PyImport_GetModuleId', ctypes.py_object, ()) -# int _PyImport_SetModule(PyObject* name, PyObject* module) -_register('_PyImport_SetModule', ctypes.c_int, (ctypes.py_object,ctypes.py_object,)) -# int _PyImport_SetModuleString(const char* name, PyObject* module) -_register('_PyImport_SetModuleString', ctypes.c_int, (ctypes.c_char_p,ctypes.py_object,)) -# void _PyImport_AcquireLock(void) -_register('_PyImport_AcquireLock', None, ()) -# int _PyImport_ReleaseLock(void) -_register('_PyImport_ReleaseLock', ctypes.c_int, ()) -# void _PyErr_WriteUnraisableMsg(const char* err_msg, PyObject* obj) -_register('_PyErr_WriteUnraisableMsg', None, (ctypes.c_char_p,ctypes.py_object,)) -# int PyFloat_Pack2(double x, char* p, int le) -_register('PyFloat_Pack2', ctypes.c_int, (ctypes.c_double,ctypes.c_char_p,ctypes.c_int,)) -# int PyFloat_Pack4(double x, char* p, int le) -_register('PyFloat_Pack4', ctypes.c_int, (ctypes.c_double,ctypes.c_char_p,ctypes.c_int,)) -# int PyFloat_Pack8(double x, char* p, int le) -_register('PyFloat_Pack8', ctypes.c_int, (ctypes.c_double,ctypes.c_char_p,ctypes.c_int,)) -# double PyFloat_Unpack2(const char* p, int le) -_register('PyFloat_Unpack2', ctypes.c_double, (ctypes.c_char_p,ctypes.c_int,)) -# double PyFloat_Unpack4(const char* p, int le) -_register('PyFloat_Unpack4', ctypes.c_double, (ctypes.c_char_p,ctypes.c_int,)) -# double PyFloat_Unpack8(const char* p, int le) -_register('PyFloat_Unpack8', ctypes.c_double, (ctypes.c_char_p,ctypes.c_int,)) -# int _PyArg_ParseStack(PyObject* const* args, Py_ssize_t nargs, const char* format, ...) -_register('_PyArg_ParseStack', ctypes.c_int) -# int _PyArg_VaParseTupleAndKeywordsFast(PyObject*, PyObject*, _PyArg_Parser*, va_list) -_register('_PyArg_VaParseTupleAndKeywordsFast', ctypes.c_int, ()) -# PyObject* const* _PyArg_UnpackKeywords(PyObject* const* args, Py_ssize_t nargs, PyObject* kwargs, PyObject* kwnames, _PyArg_Parser* parser, int minpos, int maxpos, int minkw, PyObject** buf) -_register('_PyArg_UnpackKeywords', ctypes.POINTER(ctypes.py_object), (ctypes.POINTER(ctypes.py_object),ctypes.c_ssize_t,ctypes.py_object,ctypes.py_object,ctypes.c_int,ctypes.c_int,ctypes.c_int,ctypes.POINTER(ctypes.py_object),)) -# PyObject* const* _PyArg_UnpackKeywordsWithVararg(PyObject* const* args, Py_ssize_t nargs, PyObject* kwargs, PyObject* kwnames, _PyArg_Parser* parser, int minpos, int maxpos, int minkw, int vararg, PyObject** buf) -_register('_PyArg_UnpackKeywordsWithVararg', ctypes.POINTER(ctypes.py_object), (ctypes.POINTER(ctypes.py_object),ctypes.c_ssize_t,ctypes.py_object,ctypes.py_object,ctypes.c_int,ctypes.c_int,ctypes.c_int,ctypes.c_int,ctypes.POINTER(ctypes.py_object),)) -# PyObject* _PyModule_CreateInitialized(PyModuleDef*, int apiver) -_register('_PyModule_CreateInitialized', ctypes.py_object, (ctypes.c_int,)) -# void _PyInterpreterState_RequireIDRef(PyInterpreterState*, int) -_register('_PyInterpreterState_RequireIDRef', None, ()) -# int _PyCrossInterpreterData_RegisterClass(PyTypeObject*, crossinterpdatafunc) -_register('_PyCrossInterpreterData_RegisterClass', ctypes.c_int, ()) -# void* _PyBytesWriter_WriteBytes(_PyBytesWriter* writer, void* str, const void* bytes, Py_ssize_t size) -_register('_PyBytesWriter_WriteBytes', ctypes.c_void_p, (ctypes.c_void_p,ctypes.c_void_p,ctypes.c_ssize_t,)) -# PyFrameObject* PyFrame_GetBack(PyFrameObject* frame) -_register('PyFrame_GetBack', ctypes.POINTER(PyFrameObject), (ctypes.POINTER(PyFrameObject),)) -# PyObject* PyFrame_GetLocals(PyFrameObject* frame) -_register('PyFrame_GetLocals', ctypes.py_object, (ctypes.POINTER(PyFrameObject),)) -# PyObject* PyFrame_GetGlobals(PyFrameObject* frame) -_register('PyFrame_GetGlobals', ctypes.py_object, (ctypes.POINTER(PyFrameObject),)) -# PyObject* PyFrame_GetBuiltins(PyFrameObject* frame) -_register('PyFrame_GetBuiltins', ctypes.py_object, (ctypes.POINTER(PyFrameObject),)) -# PyObject* PyFrame_GetGenerator(PyFrameObject* frame) -_register('PyFrame_GetGenerator', ctypes.py_object, (ctypes.POINTER(PyFrameObject),)) -# int PyFrame_GetLasti(PyFrameObject* frame) -_register('PyFrame_GetLasti', ctypes.c_int, (ctypes.POINTER(PyFrameObject),)) -# int _PyEval_SetTrace(PyThreadState* tstate, Py_tracefunc func, PyObject* arg) -_register('_PyEval_SetTrace', ctypes.c_int, (ctypes.POINTER(PyThreadState),ctypes.py_object,)) -# int PyEval_MergeCompilerFlags(PyCompilerFlags* cf) -_register('PyEval_MergeCompilerFlags', ctypes.c_int, ()) -# PyObject* _PyEval_EvalFrameDefault(PyThreadState* tstate, _PyInterpreterFrame* f, int exc) -_register('_PyEval_EvalFrameDefault', ctypes.py_object, (ctypes.POINTER(PyThreadState),ctypes.c_int,)) -# void _PyEval_SetSwitchInterval(unsigned long microseconds) -_register('_PyEval_SetSwitchInterval', None, (ctypes.c_ulong,)) -# unsigned long _PyEval_GetSwitchInterval(void) -_register('_PyEval_GetSwitchInterval', ctypes.c_ulong, ()) -# PyObject* _PyDictView_Intersect(PyObject* self, PyObject* other) -_register('_PyDictView_Intersect', ctypes.py_object, (ctypes.py_object,ctypes.py_object,)) -# int PyErr_WarnExplicitObject(PyObject* category, PyObject* message, PyObject* filename, int lineno, PyObject* module, PyObject* registry) -_register('PyErr_WarnExplicitObject', ctypes.c_int, (ctypes.py_object,ctypes.py_object,ctypes.py_object,ctypes.c_int,ctypes.py_object,ctypes.py_object,)) -# int PyErr_WarnExplicitFormat(PyObject* category, const char* filename, int lineno, const char* module, PyObject* registry, const char* format, ...) -_register('PyErr_WarnExplicitFormat', ctypes.c_int) -# int _PyRun_SimpleFileObject(FILE* fp, PyObject* filename, int closeit, PyCompilerFlags* flags) -_register('_PyRun_SimpleFileObject', ctypes.c_int, (ctypes.c_void_p,ctypes.py_object,ctypes.c_int,)) -# PyObject* _PySys_GetAttr(PyThreadState* tstate, PyObject* name) -_register('_PySys_GetAttr', ctypes.py_object, (ctypes.POINTER(PyThreadState),ctypes.py_object,)) -# int PySys_Audit(const char* event, const char* argFormat, ...) -_register('PySys_Audit', ctypes.c_int) -# void _PyTuple_DebugMallocStats(FILE* out) -_register('_PyTuple_DebugMallocStats', None, (ctypes.c_void_p,)) -# int PyType_SUPPORTS_WEAKREFS(PyTypeObject* type) -_register('PyType_SUPPORTS_WEAKREFS', ctypes.c_int, (ctypes.POINTER(PyTypeObject),)) -# PyObject** PyObject_GET_WEAKREFS_LISTPTR(PyObject* op) -_register('PyObject_GET_WEAKREFS_LISTPTR', ctypes.POINTER(ctypes.py_object), (ctypes.py_object,)) -# PyObject* _PyNumber_Index(PyObject* o) -_register('_PyNumber_Index', ctypes.py_object, (ctypes.py_object,)) -# PyObject* PyFile_OpenCode(const char* utf8path) -_register('PyFile_OpenCode', ctypes.py_object, (ctypes.c_char_p,)) -# PyObject* PyFile_OpenCodeObject(PyObject* path) -_register('PyFile_OpenCodeObject', ctypes.py_object, (ctypes.py_object,)) -# int PyFile_SetOpenCodeHook(Py_OpenCodeHookFunction hook, void* userData) -_register('PyFile_SetOpenCodeHook', ctypes.c_int, (ctypes.c_void_p,)) -# void* PyMem_RawMalloc(size_t size) -_register('PyMem_RawMalloc', ctypes.c_void_p, (ctypes.c_size_t,)) -# void* PyMem_RawCalloc(size_t nelem, size_t elsize) -_register('PyMem_RawCalloc', ctypes.c_void_p, (ctypes.c_size_t,ctypes.c_size_t,)) -# void* PyMem_RawRealloc(void* ptr, size_t new_size) -_register('PyMem_RawRealloc', ctypes.c_void_p, (ctypes.c_void_p,ctypes.c_size_t,)) -# void PyMem_RawFree(void* ptr) -_register('PyMem_RawFree', None, (ctypes.c_void_p,)) -# void PyMem_SetupDebugHooks(void) -_register('PyMem_SetupDebugHooks', None, ()) -# FILE* _Py_fopen_obj(PyObject* path, const char* mode) -_register('_Py_fopen_obj', ctypes.c_void_p, (ctypes.py_object,ctypes.c_char_p,)) -# PyCodeObject* _PyAST_Compile(_mod* mod, PyObject* filename, PyCompilerFlags* flags, int optimize, _arena* arena) -_register('_PyAST_Compile', ctypes.POINTER(PyCodeObject), (ctypes.py_object,ctypes.c_int,)) -# int _PySys_Audit(PyThreadState* tstate, const char* event, const char* argFormat, ...) -_register('_PySys_Audit', ctypes.c_int) -# double _Py_dg_strtod(const char* str, char** ptr) -_register('_Py_dg_strtod', ctypes.c_double, (ctypes.c_char_p,ctypes.POINTER(ctypes.c_char_p),)) -# char* _Py_dg_dtoa(double d, int mode, int ndigits, int* decpt, int* sign, char** rve) -_register('_Py_dg_dtoa', ctypes.c_char_p, (ctypes.c_double,ctypes.c_int,ctypes.c_int,ctypes.POINTER(ctypes.c_int),ctypes.POINTER(ctypes.c_int),ctypes.POINTER(ctypes.c_char_p),)) -# void _Py_dg_freedtoa(char* s) -_register('_Py_dg_freedtoa', None, (ctypes.c_char_p,)) -# double _Py_dg_stdnan(int sign) -_register('_Py_dg_stdnan', ctypes.c_double, (ctypes.c_int,)) -# double _Py_dg_infinity(int sign) -_register('_Py_dg_infinity', ctypes.c_double, (ctypes.c_int,)) -# PyObject* _PyObject_Call_Prepend(PyThreadState* tstate, PyObject* callable, PyObject* obj, PyObject* args, PyObject* kwargs) -_register('_PyObject_Call_Prepend', ctypes.py_object, (ctypes.POINTER(PyThreadState),ctypes.py_object,ctypes.py_object,ctypes.py_object,ctypes.py_object,)) -# PyObject* _PyObject_FastCallDictTstate(PyThreadState* tstate, PyObject* callable, PyObject* const* args, size_t nargsf, PyObject* kwargs) -_register('_PyObject_FastCallDictTstate', ctypes.py_object, (ctypes.POINTER(PyThreadState),ctypes.py_object,ctypes.POINTER(ctypes.py_object),ctypes.c_size_t,ctypes.py_object,)) -# PyObject* _PyObject_Call(PyThreadState* tstate, PyObject* callable, PyObject* args, PyObject* kwargs) -_register('_PyObject_Call', ctypes.py_object, (ctypes.POINTER(PyThreadState),ctypes.py_object,ctypes.py_object,ctypes.py_object,)) -# int _PyObject_DebugMallocStats(FILE* out) -_register('_PyObject_DebugMallocStats', ctypes.c_int, (ctypes.c_void_p,)) -# void _PyPathConfig_ClearGlobal(void) -_register('_PyPathConfig_ClearGlobal', None, ()) -# PyObject* _PyNamespace_New(PyObject* kwds) -_register('_PyNamespace_New', ctypes.py_object, (ctypes.py_object,)) -# int _PyType_CheckConsistency(PyTypeObject* type) -_register('_PyType_CheckConsistency', ctypes.c_int, (ctypes.POINTER(PyTypeObject),)) -# int _PyDict_CheckConsistency(PyObject* mp, int check_content) -_register('_PyDict_CheckConsistency', ctypes.c_int, (ctypes.py_object,ctypes.c_int,)) -# PyObject* _Py_strhex(constchar* argbuf, const Py_ssize_t arglen) -_register('_Py_strhex', ctypes.py_object, (ctypes.c_ssize_t,)) -# PyObject* _Py_strhex_bytes(const char* argbuf, const Py_ssize_t arglen) -_register('_Py_strhex_bytes', ctypes.py_object, (ctypes.c_char_p,ctypes.c_ssize_t,)) -# PyObject* _Py_strhex_with_sep(const char* argbuf, const Py_ssize_t arglen, PyObject* sep, const int bytes_per_group) -_register('_Py_strhex_with_sep', ctypes.py_object, (ctypes.c_char_p,ctypes.c_ssize_t,ctypes.py_object,ctypes.c_int,)) -# PyObject* _Py_strhex_bytes_with_sep(const char* argbuf, const Py_ssize_t arglen, PyObject* sep, const int bytes_per_group) -_register('_Py_strhex_bytes_with_sep', ctypes.py_object, (ctypes.c_char_p,ctypes.c_ssize_t,ctypes.py_object,ctypes.c_int,)) diff --git a/src/pointers/_utils.py b/src/pointers/_utils.py deleted file mode 100644 index 8cc7560..0000000 --- a/src/pointers/_utils.py +++ /dev/null @@ -1,171 +0,0 @@ -import ctypes -from collections.abc import Callable -from types import FunctionType, MethodType -from typing import Any, Dict, Type, Union - -from _pointers import force_set_attr as _force_set_attr - -from .exceptions import InvalidSizeError - -__all__ = ( - "attempt_decode", - "move_to_mem", - "map_type", - "get_mapped", - "is_mappable", - "get_py", - "make_py", -) - -_C_TYPES: Dict[Type[Any], Type["ctypes._CData"]] = { - bytes: ctypes.c_char_p, - str: ctypes.c_wchar_p, - int: ctypes.c_int, - float: ctypes.c_float, - bool: ctypes.c_bool, - object: ctypes.py_object, - type: ctypes.py_object -} - -_PY_TYPES: Dict[Type["ctypes._CData"], type] = { - ctypes.c_bool: bool, - ctypes.c_char: bytes, - ctypes.c_wchar: str, - ctypes.c_ubyte: int, - ctypes.c_short: int, - ctypes.c_int: int, - ctypes.c_uint: int, - ctypes.c_long: int, - ctypes.c_ulong: int, - ctypes.c_longlong: int, - ctypes.c_ulonglong: int, - ctypes.c_size_t: int, - ctypes.c_ssize_t: int, - ctypes.c_float: float, - ctypes.c_double: float, - ctypes.c_longdouble: float, - ctypes.c_char_p: bytes, - ctypes.c_wchar_p: str, - ctypes.c_void_p: int, - ctypes.py_object: Any, # type: ignore -} - - -def move_to_mem( - ptr: "ctypes._PointerLike", - stream: bytes, - *, - unsafe: bool = False, - target: str = "memory allocation", -): - """Move data to a C pointer.""" - - slen = len(stream) - plen = len(ptr.contents) # type: ignore - - if (slen > plen) and (not unsafe): - raise InvalidSizeError( - f"object is of size {slen}, while {target} is {plen}", - ) - - ctypes.memmove(ptr, stream, slen) - - -def attempt_decode(data: bytes) -> Union[str, bytes]: - """Attempt to decode a string of bytes.""" - try: - return data.decode() - except UnicodeDecodeError: - return data - - -def map_type(data: Any) -> "ctypes._CData": - """Map the specified data to a C type.""" - typ = get_mapped(type(data)) - - try: - return typ(data) # type: ignore - except TypeError: - return ctypes.py_object(data) - -def get_mapped(typ: Any) -> "Type[ctypes._CData]": - """Get the C mapped value of the given type.""" - from .c_pointer import VoidPointer - - if getattr(typ, "__origin__", None) is Callable: - args = list(typ.__args__) - res = args.pop(-1) - return ctypes.CFUNCTYPE(get_mapped(res), *map(get_mapped, args)) - - if type(typ) in {FunctionType, MethodType}: - hints = typ.__annotations__.copy() - try: - res = hints.pop("return") - except KeyError as e: - raise TypeError( - "return type annotation is required to convert to a C function" # noqa - ) from e - - args = hints.values() - return ctypes.CFUNCTYPE( - get_mapped(res) if res else None, - *map(get_mapped, args), - ) - - # VoidPointer needs to be passed here to stop circular imports - return {**_C_TYPES, VoidPointer: ctypes.c_void_p}.get( # type: ignore - typ, - ) or ctypes.py_object - - -def is_mappable(typ: Any) -> bool: - """Whether the specified type is mappable to C.""" - try: - get_mapped(typ) - return True - except ValueError: - return False - - -def get_py( - data: Type["ctypes._CData"], -) -> Type[Any]: - """Map the specified C type to a Python type.""" - from .base_pointers import BaseCPointer - - if data.__name__.startswith("LP_"): - return BaseCPointer - - try: - return _PY_TYPES[data] - except KeyError as e: - raise ValueError( - f"{data} is not a valid ctypes type", - ) from e - - -def make_py(data: "ctypes._CData"): - """Convert the target C value to a Python object.""" - typ = get_py(type(data)) - res = typ(data) - - if typ is bytes: - res = attempt_decode(res) - - return res - - -def force_set_attr(typ: Type[Any], key: str, value: Any) -> None: - """Force setting an attribute on the target type.""" - - if not isinstance(typ, type): - raise ValueError( - f"{typ} does not derive from type (did you pass an instance and not a class)?", # noqa - ) - - _force_set_attr(typ, key, value) - - -def deref(address: int) -> Any: - """Get the value at the target address.""" - return ctypes.cast(address, ctypes.py_object).value diff --git a/src/pointers/api_bindings.py b/src/pointers/api_bindings.py deleted file mode 100644 index 6fd71be..0000000 --- a/src/pointers/api_bindings.py +++ /dev/null @@ -1,5158 +0,0 @@ -from typing import Callable, TypeVar, Union - -from ._pyapi import API_FUNCS, Func -from .base_pointers import BaseObjectPointer -from .bindings import ( - CharLike, - PointerLike, - StringLike, - binding_base, - make_char, - make_string, -) -from .std_structs import * -from .structure import StructPointer - - -def api_binding_base(data: Func, *args): - func = data[0] - - if not func: - name: str = data[2] - minver = data[1] - - raise NotImplementedError( - f"{name} is only supported on versions {data[1]}+" - if minver - else f"{name} is not supported on this version", - ) - - return binding_base(func, *args) - - -class DumbassError(Exception): - """lmao""" - - -class _CallBase: - def __init__(self): - raise DumbassError("this is a namespace") - - -T = TypeVar("T") -PyObjectLike = Union[T, BaseObjectPointer[T]] - - -def _deref_maybe(ob: PyObjectLike[T]) -> T: - if isinstance(ob, BaseObjectPointer): - return ~ob - return ob - - -# autogenerated -__all__ = ( - "PyAIter", - "PyArg", - "PyBool", - "PyBuffer", - "PyByteArray", - "PyBytes", - "PyCallIter", - "PyCallable", - "PyCapsule", - "PyCodec", - "PyComplex", - "PyDescr", - "PyDictProxy", - "PyDict", - "PyErr", - "PyEval", - "PyException", - "PyFile", - "PyFloat", - "PyFrame", - "PyFrozenSet", - "PyGC", - "PyGILState", - "PyImport", - "PyIndex", - "PyInterpreterState", - "PyIter", - "PyList", - "PyLong", - "PyMapping", - "PyMem", - "PyMemoryView", - "PyModuleDef", - "PyModule", - "PyNumber", - "PyOS", - "PyObject", - "PySeqIter", - "PySequence", - "PySet", - "PySlice", - "PyState", - "PyStructSequence", - "PySys", - "PyThreadState", - "PyThread", - "PyTuple", - "PyType", - "PyUnicodeDecodeError", - "PyUnicodeEncodeError", - "PyUnicodeTranslateError", - "PyUnicode", - "PyWeakref", - "Py", - "PyContext", - "_PyWarnings", - "_PyFrame", - "_Py", - "PyCompile", - "_PyTraceback", - "_PyImport", - "_PyErr", - "_PyInterpreterState", - "_PyBytesWriter", - "_PyEval", - "_PyDictView", - "_PyRun", - "_PySys", - "_PyTuple", - "_PyNumber", - "_PyAST", - "_PyStructSequence", - "_PyObject", - "_PyType", - "_PyDict", -) - - -class PyAIter(_CallBase): - """Namespace containing API functions prefixed with `PyAIter_`""" - - # PyAIter_Check - @staticmethod - def check(o: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyAIter_Check"], _deref_maybe(o)) - - -class PyArg(_CallBase): - """Namespace containing API functions prefixed with `PyArg_`""" - - # PyArg_VaParse - @staticmethod - def va_parse(args: PyObjectLike, format: StringLike, vargs: PointerLike) -> int: - return api_binding_base( - API_FUNCS["PyArg_VaParse"], _deref_maybe(args), make_string(format), vargs - ) - - # PyArg_VaParseTupleAndKeywords - @staticmethod - def va_parse_tuple_and_keywords( - args: PyObjectLike, - kw: PyObjectLike, - format: StringLike, - keywords: PointerLike, - vargs: PointerLike, - ) -> int: - return api_binding_base( - API_FUNCS["PyArg_VaParseTupleAndKeywords"], - _deref_maybe(args), - _deref_maybe(kw), - make_string(format), - keywords, - vargs, - ) - - -class PyBool(_CallBase): - """Namespace containing API functions prefixed with `PyBool_`""" - - # PyBool_FromLong - @staticmethod - def from_long(v: int) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyBool_FromLong"], v) - - -class PyBuffer(_CallBase): - """Namespace containing API functions prefixed with `PyBuffer_`""" - - # PyBuffer_FillContiguousStrides - @staticmethod - def fill_contiguous_strides( - ndims: int, - shape: PointerLike, - strides: PointerLike, - itemsize: int, - order: CharLike, - ) -> None: - return api_binding_base( - API_FUNCS["PyBuffer_FillContiguousStrides"], - ndims, - shape, - strides, - itemsize, - make_char(order), - ) - - # PyBuffer_FillInfo - @staticmethod - def fill_info( - view: StructPointer[Buffer], - exporter: PyObjectLike, - buf: PointerLike, - len: int, - readonly: int, - flags: int, - ) -> int: - return api_binding_base( - API_FUNCS["PyBuffer_FillInfo"], - view, - _deref_maybe(exporter), - buf, - len, - readonly, - flags, - ) - - # PyBuffer_FromContiguous - @staticmethod - def from_contiguous( - view: StructPointer[Buffer], buf: PointerLike, len: int, fort: CharLike - ) -> int: - return api_binding_base( - API_FUNCS["PyBuffer_FromContiguous"], view, buf, len, make_char(fort) - ) - - # PyBuffer_GetPointer - @staticmethod - def get_pointer(view: StructPointer[Buffer], indices: PointerLike) -> PointerLike: - return api_binding_base(API_FUNCS["PyBuffer_GetPointer"], view, indices) - - # PyBuffer_IsContiguous - @staticmethod - def is_contiguous(view: StructPointer[Buffer], order: CharLike) -> int: - return api_binding_base( - API_FUNCS["PyBuffer_IsContiguous"], view, make_char(order) - ) - - # PyBuffer_Release - @staticmethod - def release(view: StructPointer[Buffer]) -> None: - return api_binding_base(API_FUNCS["PyBuffer_Release"], view) - - # PyBuffer_SizeFromFormat - @staticmethod - def size_from_format(format: StringLike) -> int: - return api_binding_base( - API_FUNCS["PyBuffer_SizeFromFormat"], make_string(format) - ) - - # PyBuffer_ToContiguous - @staticmethod - def to_contiguous( - buf: PointerLike, src: StructPointer[Buffer], len: int, order: CharLike - ) -> int: - return api_binding_base( - API_FUNCS["PyBuffer_ToContiguous"], buf, src, len, make_char(order) - ) - - -class PyByteArray(_CallBase): - """Namespace containing API functions prefixed with `PyByteArray_`""" - - # PyByteArray_AsString - @staticmethod - def as_string(bytearray: PyObjectLike) -> StringLike: - return api_binding_base( - API_FUNCS["PyByteArray_AsString"], _deref_maybe(bytearray) - ) - - # PyByteArray_Concat - @staticmethod - def concat(a: PyObjectLike, b: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyByteArray_Concat"], _deref_maybe(a), _deref_maybe(b) - ) - - # PyByteArray_FromObject - @staticmethod - def from_object(o: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyByteArray_FromObject"], _deref_maybe(o)) - - # PyByteArray_FromStringAndSize - @staticmethod - def from_string_and_size(string: StringLike, len: int) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyByteArray_FromStringAndSize"], make_string(string), len - ) - - # PyByteArray_Resize - @staticmethod - def resize(bytearray: PyObjectLike, len: int) -> int: - return api_binding_base( - API_FUNCS["PyByteArray_Resize"], _deref_maybe(bytearray), len - ) - - # PyByteArray_Size - @staticmethod - def size(bytearray: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyByteArray_Size"], _deref_maybe(bytearray)) - - -class PyBytes(_CallBase): - """Namespace containing API functions prefixed with `PyBytes_`""" - - # PyBytes_AsString - @staticmethod - def as_string(o: PyObjectLike) -> StringLike: - return api_binding_base(API_FUNCS["PyBytes_AsString"], _deref_maybe(o)) - - # PyBytes_AsStringAndSize - @staticmethod - def as_string_and_size( - obj: PyObjectLike, buffer: PointerLike, length: PointerLike - ) -> int: - return api_binding_base( - API_FUNCS["PyBytes_AsStringAndSize"], _deref_maybe(obj), buffer, length - ) - - # PyBytes_Concat - @staticmethod - def concat(bytes: PointerLike, newpart: PyObjectLike) -> None: - return api_binding_base( - API_FUNCS["PyBytes_Concat"], bytes, _deref_maybe(newpart) - ) - - # PyBytes_ConcatAndDel - @staticmethod - def concat_and_del(bytes: PointerLike, newpart: PyObjectLike) -> None: - return api_binding_base( - API_FUNCS["PyBytes_ConcatAndDel"], bytes, _deref_maybe(newpart) - ) - - # PyBytes_FromFormatV - @staticmethod - def from_format_v(format: StringLike, vargs: PointerLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyBytes_FromFormatV"], make_string(format), vargs - ) - - # PyBytes_FromObject - @staticmethod - def from_object(o: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyBytes_FromObject"], _deref_maybe(o)) - - # PyBytes_FromString - @staticmethod - def from_string(v: StringLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyBytes_FromString"], make_string(v)) - - # PyBytes_FromStringAndSize - @staticmethod - def from_string_and_size(v: StringLike, len: int) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyBytes_FromStringAndSize"], make_string(v), len - ) - - # PyBytes_Size - @staticmethod - def size(o: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyBytes_Size"], _deref_maybe(o)) - - -class PyCallIter(_CallBase): - """Namespace containing API functions prefixed with `PyCallIter_`""" - - # PyCallIter_New - @staticmethod - def new(callable: PyObjectLike, sentinel: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyCallIter_New"], _deref_maybe(callable), _deref_maybe(sentinel) - ) - - -class PyCallable(_CallBase): - """Namespace containing API functions prefixed with `PyCallable_`""" - - # PyCallable_Check - @staticmethod - def check(o: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyCallable_Check"], _deref_maybe(o)) - - -class PyCapsule(_CallBase): - """Namespace containing API functions prefixed with `PyCapsule_`""" - - # PyCapsule_GetContext - @staticmethod - def get_context(capsule: PyObjectLike) -> PointerLike: - return api_binding_base( - API_FUNCS["PyCapsule_GetContext"], _deref_maybe(capsule) - ) - - # PyCapsule_GetDestructor - @staticmethod - def get_destructor(capsule: PyObjectLike) -> PointerLike: - return api_binding_base( - API_FUNCS["PyCapsule_GetDestructor"], _deref_maybe(capsule) - ) - - # PyCapsule_GetName - @staticmethod - def get_name(capsule: PyObjectLike) -> StringLike: - return api_binding_base(API_FUNCS["PyCapsule_GetName"], _deref_maybe(capsule)) - - # PyCapsule_GetPointer - @staticmethod - def get_pointer(capsule: PyObjectLike, name: StringLike) -> PointerLike: - return api_binding_base( - API_FUNCS["PyCapsule_GetPointer"], _deref_maybe(capsule), make_string(name) - ) - - # PyCapsule_Import - @staticmethod - def import_(name: StringLike, no_block: int) -> PointerLike: - return api_binding_base( - API_FUNCS["PyCapsule_Import"], make_string(name), no_block - ) - - # PyCapsule_IsValid - @staticmethod - def is_valid(capsule: PyObjectLike, name: StringLike) -> int: - return api_binding_base( - API_FUNCS["PyCapsule_IsValid"], _deref_maybe(capsule), make_string(name) - ) - - # PyCapsule_New - @staticmethod - def new( - pointer: PointerLike, name: StringLike, destructor: PointerLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyCapsule_New"], pointer, make_string(name), destructor - ) - - # PyCapsule_SetContext - @staticmethod - def set_context(capsule: PyObjectLike, context: PointerLike) -> int: - return api_binding_base( - API_FUNCS["PyCapsule_SetContext"], _deref_maybe(capsule), context - ) - - # PyCapsule_SetDestructor - @staticmethod - def set_destructor(capsule: PyObjectLike, destructor: PointerLike) -> int: - return api_binding_base( - API_FUNCS["PyCapsule_SetDestructor"], _deref_maybe(capsule), destructor - ) - - # PyCapsule_SetName - @staticmethod - def set_name(capsule: PyObjectLike, name: StringLike) -> int: - return api_binding_base( - API_FUNCS["PyCapsule_SetName"], _deref_maybe(capsule), make_string(name) - ) - - # PyCapsule_SetPointer - @staticmethod - def set_pointer(capsule: PyObjectLike, pointer: PointerLike) -> int: - return api_binding_base( - API_FUNCS["PyCapsule_SetPointer"], _deref_maybe(capsule), pointer - ) - - -class PyCodec(_CallBase): - """Namespace containing API functions prefixed with `PyCodec_`""" - - # PyCodec_BackslashReplaceErrors - @staticmethod - def backslash_replace_errors(exc: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyCodec_BackslashReplaceErrors"], _deref_maybe(exc) - ) - - # PyCodec_Decode - @staticmethod - def decode( - object: PyObjectLike, encoding: StringLike, errors: StringLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyCodec_Decode"], - _deref_maybe(object), - make_string(encoding), - make_string(errors), - ) - - # PyCodec_Decoder - @staticmethod - def decoder(encoding: StringLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyCodec_Decoder"], make_string(encoding)) - - # PyCodec_Encode - @staticmethod - def encode( - object: PyObjectLike, encoding: StringLike, errors: StringLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyCodec_Encode"], - _deref_maybe(object), - make_string(encoding), - make_string(errors), - ) - - # PyCodec_Encoder - @staticmethod - def encoder(encoding: StringLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyCodec_Encoder"], make_string(encoding)) - - # PyCodec_IgnoreErrors - @staticmethod - def ignore_errors(exc: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyCodec_IgnoreErrors"], _deref_maybe(exc)) - - # PyCodec_IncrementalDecoder - @staticmethod - def incremental_decoder(encoding: StringLike, errors: StringLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyCodec_IncrementalDecoder"], - make_string(encoding), - make_string(errors), - ) - - # PyCodec_IncrementalEncoder - @staticmethod - def incremental_encoder(encoding: StringLike, errors: StringLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyCodec_IncrementalEncoder"], - make_string(encoding), - make_string(errors), - ) - - # PyCodec_KnownEncoding - @staticmethod - def known_encoding(encoding: StringLike) -> int: - return api_binding_base( - API_FUNCS["PyCodec_KnownEncoding"], make_string(encoding) - ) - - # PyCodec_LookupError - @staticmethod - def lookup_error(name: StringLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyCodec_LookupError"], make_string(name)) - - # PyCodec_NameReplaceErrors - @staticmethod - def name_replace_errors(exc: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyCodec_NameReplaceErrors"], _deref_maybe(exc) - ) - - # PyCodec_Register - @staticmethod - def register(search_function: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyCodec_Register"], _deref_maybe(search_function) - ) - - # PyCodec_RegisterError - @staticmethod - def register_error(name: StringLike, error: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyCodec_RegisterError"], make_string(name), _deref_maybe(error) - ) - - # PyCodec_ReplaceErrors - @staticmethod - def replace_errors(exc: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyCodec_ReplaceErrors"], _deref_maybe(exc)) - - # PyCodec_StreamReader - @staticmethod - def stream_reader( - encoding: StringLike, stream: PyObjectLike, errors: StringLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyCodec_StreamReader"], - make_string(encoding), - _deref_maybe(stream), - make_string(errors), - ) - - # PyCodec_StreamWriter - @staticmethod - def stream_writer( - encoding: StringLike, stream: PyObjectLike, errors: StringLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyCodec_StreamWriter"], - make_string(encoding), - _deref_maybe(stream), - make_string(errors), - ) - - # PyCodec_StrictErrors - @staticmethod - def strict_errors(exc: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyCodec_StrictErrors"], _deref_maybe(exc)) - - # PyCodec_Unregister - @staticmethod - def unregister(search_function: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyCodec_Unregister"], _deref_maybe(search_function) - ) - - # PyCodec_XMLCharRefReplaceErrors - @staticmethod - def x_m_l_char_ref_replace_errors(exc: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyCodec_XMLCharRefReplaceErrors"], _deref_maybe(exc) - ) - - -class PyComplex(_CallBase): - """Namespace containing API functions prefixed with `PyComplex_`""" - - # PyComplex_FromDoubles - @staticmethod - def from_doubles(real: int, imag: int) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyComplex_FromDoubles"], real, imag) - - # PyComplex_ImagAsDouble - @staticmethod - def imag_as_double(op: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyComplex_ImagAsDouble"], _deref_maybe(op)) - - # PyComplex_RealAsDouble - @staticmethod - def real_as_double(op: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyComplex_RealAsDouble"], _deref_maybe(op)) - - -class PyDescr(_CallBase): - """Namespace containing API functions prefixed with `PyDescr_`""" - - # PyDescr_NewClassMethod - @staticmethod - def new_class_method( - type: StructPointer[TypeObject], method: StructPointer[MethodDef] - ) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyDescr_NewClassMethod"], type, method) - - # PyDescr_NewGetSet - @staticmethod - def new_get_set( - type: StructPointer[TypeObject], getset: StructPointer[GetSetDef] - ) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyDescr_NewGetSet"], type, getset) - - # PyDescr_NewMember - @staticmethod - def new_member(type: StructPointer[TypeObject]) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyDescr_NewMember"], type) - - # PyDescr_NewMethod - @staticmethod - def new_method( - type: StructPointer[TypeObject], meth: StructPointer[MethodDef] - ) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyDescr_NewMethod"], type, meth) - - -class PyDictProxy(_CallBase): - """Namespace containing API functions prefixed with `PyDictProxy_`""" - - # PyDictProxy_New - @staticmethod - def new(mapping: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyDictProxy_New"], _deref_maybe(mapping)) - - -class PyDict(_CallBase): - """Namespace containing API functions prefixed with `PyDict_`""" - - # PyDict_Clear - @staticmethod - def clear(p: PyObjectLike) -> None: - return api_binding_base(API_FUNCS["PyDict_Clear"], _deref_maybe(p)) - - # PyDict_Contains - @staticmethod - def contains(p: PyObjectLike, key: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyDict_Contains"], _deref_maybe(p), _deref_maybe(key) - ) - - # PyDict_Copy - @staticmethod - def copy(p: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyDict_Copy"], _deref_maybe(p)) - - # PyDict_DelItem - @staticmethod - def del_item(p: PyObjectLike, key: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyDict_DelItem"], _deref_maybe(p), _deref_maybe(key) - ) - - # PyDict_DelItemString - @staticmethod - def del_item_string(p: PyObjectLike, key: StringLike) -> int: - return api_binding_base( - API_FUNCS["PyDict_DelItemString"], _deref_maybe(p), make_string(key) - ) - - # PyDict_GetItem - @staticmethod - def get_item(p: PyObjectLike, key: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyDict_GetItem"], _deref_maybe(p), _deref_maybe(key) - ) - - # PyDict_GetItemString - @staticmethod - def get_item_string(p: PyObjectLike, key: StringLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyDict_GetItemString"], _deref_maybe(p), make_string(key) - ) - - # PyDict_GetItemWithError - @staticmethod - def get_item_with_error(p: PyObjectLike, key: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyDict_GetItemWithError"], _deref_maybe(p), _deref_maybe(key) - ) - - # PyDict_Items - @staticmethod - def items(p: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyDict_Items"], _deref_maybe(p)) - - # PyDict_Keys - @staticmethod - def keys(p: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyDict_Keys"], _deref_maybe(p)) - - # PyDict_Merge - @staticmethod - def merge(a: PyObjectLike, b: PyObjectLike, override: int) -> int: - return api_binding_base( - API_FUNCS["PyDict_Merge"], _deref_maybe(a), _deref_maybe(b), override - ) - - # PyDict_MergeFromSeq2 - @staticmethod - def merge_from_seq2(a: PyObjectLike, seq2: PyObjectLike, override: int) -> int: - return api_binding_base( - API_FUNCS["PyDict_MergeFromSeq2"], - _deref_maybe(a), - _deref_maybe(seq2), - override, - ) - - # PyDict_New - @staticmethod - def new() -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyDict_New"], - ) - - # PyDict_Next - @staticmethod - def next( - p: PyObjectLike, ppos: PointerLike, pkey: PointerLike, pvalue: PointerLike - ) -> int: - return api_binding_base( - API_FUNCS["PyDict_Next"], _deref_maybe(p), ppos, pkey, pvalue - ) - - # PyDict_SetItem - @staticmethod - def set_item(p: PyObjectLike, key: PyObjectLike, val: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyDict_SetItem"], - _deref_maybe(p), - _deref_maybe(key), - _deref_maybe(val), - ) - - # PyDict_SetItemString - @staticmethod - def set_item_string(p: PyObjectLike, key: StringLike, val: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyDict_SetItemString"], - _deref_maybe(p), - make_string(key), - _deref_maybe(val), - ) - - # PyDict_Size - @staticmethod - def size(p: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyDict_Size"], _deref_maybe(p)) - - # PyDict_Update - @staticmethod - def update(a: PyObjectLike, b: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyDict_Update"], _deref_maybe(a), _deref_maybe(b) - ) - - # PyDict_Values - @staticmethod - def values(p: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyDict_Values"], _deref_maybe(p)) - - -class PyErr(_CallBase): - """Namespace containing API functions prefixed with `PyErr_`""" - - # PyErr_BadArgument - @staticmethod - def bad_argument() -> int: - return api_binding_base( - API_FUNCS["PyErr_BadArgument"], - ) - - # PyErr_BadInternalCall - @staticmethod - def bad_internal_call() -> None: - return api_binding_base( - API_FUNCS["PyErr_BadInternalCall"], - ) - - # PyErr_CheckSignals - @staticmethod - def check_signals() -> int: - return api_binding_base( - API_FUNCS["PyErr_CheckSignals"], - ) - - # PyErr_Clear - @staticmethod - def clear() -> None: - return api_binding_base( - API_FUNCS["PyErr_Clear"], - ) - - # PyErr_ExceptionMatches - @staticmethod - def exception_matches(exc: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyErr_ExceptionMatches"], _deref_maybe(exc)) - - # PyErr_Fetch - @staticmethod - def fetch(ptype: PointerLike, pvalue: PointerLike, ptraceback: PointerLike) -> None: - return api_binding_base(API_FUNCS["PyErr_Fetch"], ptype, pvalue, ptraceback) - - # PyErr_FormatV - @staticmethod - def format_v( - exception: PyObjectLike, format: StringLike, vargs: PointerLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyErr_FormatV"], - _deref_maybe(exception), - make_string(format), - vargs, - ) - - # PyErr_GetExcInfo - @staticmethod - def get_exc_info( - ptype: PointerLike, pvalue: PointerLike, ptraceback: PointerLike - ) -> None: - return api_binding_base( - API_FUNCS["PyErr_GetExcInfo"], ptype, pvalue, ptraceback - ) - - # PyErr_GivenExceptionMatches - @staticmethod - def given_exception_matches(given: PyObjectLike, exc: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyErr_GivenExceptionMatches"], - _deref_maybe(given), - _deref_maybe(exc), - ) - - # PyErr_NewException - @staticmethod - def new_exception( - name: StringLike, base: PyObjectLike, dict: PyObjectLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyErr_NewException"], - make_string(name), - _deref_maybe(base), - _deref_maybe(dict), - ) - - # PyErr_NewExceptionWithDoc - @staticmethod - def new_exception_with_doc( - name: StringLike, doc: StringLike, base: PyObjectLike, dict: PyObjectLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyErr_NewExceptionWithDoc"], - make_string(name), - make_string(doc), - _deref_maybe(base), - _deref_maybe(dict), - ) - - # PyErr_NoMemory - @staticmethod - def no_memory() -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyErr_NoMemory"], - ) - - # PyErr_NormalizeException - @staticmethod - def normalize_exception( - exc: PointerLike, val: PointerLike, tb: PointerLike - ) -> None: - return api_binding_base(API_FUNCS["PyErr_NormalizeException"], exc, val, tb) - - # PyErr_Occurred - @staticmethod - def occurred() -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyErr_Occurred"], - ) - - # PyErr_Print - @staticmethod - def print() -> None: - return api_binding_base( - API_FUNCS["PyErr_Print"], - ) - - # PyErr_PrintEx - @staticmethod - def print_ex(set_sys_last_vars: int) -> None: - return api_binding_base(API_FUNCS["PyErr_PrintEx"], set_sys_last_vars) - - # PyErr_Restore - @staticmethod - def restore( - type: PyObjectLike, value: PyObjectLike, traceback: PyObjectLike - ) -> None: - return api_binding_base( - API_FUNCS["PyErr_Restore"], - _deref_maybe(type), - _deref_maybe(value), - _deref_maybe(traceback), - ) - - # PyErr_SetExcInfo - @staticmethod - def set_exc_info( - type: PyObjectLike, value: PyObjectLike, traceback: PyObjectLike - ) -> None: - return api_binding_base( - API_FUNCS["PyErr_SetExcInfo"], - _deref_maybe(type), - _deref_maybe(value), - _deref_maybe(traceback), - ) - - # PyErr_SetFromErrno - @staticmethod - def set_from_errno(type: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyErr_SetFromErrno"], _deref_maybe(type)) - - # PyErr_SetFromErrnoWithFilename - @staticmethod - def set_from_errno_with_filename( - type: PyObjectLike, filename: StringLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyErr_SetFromErrnoWithFilename"], - _deref_maybe(type), - make_string(filename), - ) - - # PyErr_SetFromErrnoWithFilenameObject - @staticmethod - def set_from_errno_with_filename_object( - type: PyObjectLike, filenameObject: PyObjectLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyErr_SetFromErrnoWithFilenameObject"], - _deref_maybe(type), - _deref_maybe(filenameObject), - ) - - # PyErr_SetFromErrnoWithFilenameObjects - @staticmethod - def set_from_errno_with_filename_objects( - type: PyObjectLike, filenameObject: PyObjectLike, filenameObject2: PyObjectLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyErr_SetFromErrnoWithFilenameObjects"], - _deref_maybe(type), - _deref_maybe(filenameObject), - _deref_maybe(filenameObject2), - ) - - # PyErr_SetImportError - @staticmethod - def set_import_error( - msg: PyObjectLike, name: PyObjectLike, path: PyObjectLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyErr_SetImportError"], - _deref_maybe(msg), - _deref_maybe(name), - _deref_maybe(path), - ) - - # PyErr_SetImportErrorSubclass - @staticmethod - def set_import_error_subclass( - exception: PyObjectLike, - msg: PyObjectLike, - name: PyObjectLike, - path: PyObjectLike, - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyErr_SetImportErrorSubclass"], - _deref_maybe(exception), - _deref_maybe(msg), - _deref_maybe(name), - _deref_maybe(path), - ) - - # PyErr_SetInterrupt - @staticmethod - def set_interrupt() -> None: - return api_binding_base( - API_FUNCS["PyErr_SetInterrupt"], - ) - - # PyErr_SetInterruptEx - @staticmethod - def set_interrupt_ex(signum: int) -> int: - return api_binding_base(API_FUNCS["PyErr_SetInterruptEx"], signum) - - # PyErr_SetNone - @staticmethod - def set_none(type: PyObjectLike) -> None: - return api_binding_base(API_FUNCS["PyErr_SetNone"], _deref_maybe(type)) - - # PyErr_SetObject - @staticmethod - def set_object(type: PyObjectLike, value: PyObjectLike) -> None: - return api_binding_base( - API_FUNCS["PyErr_SetObject"], _deref_maybe(type), _deref_maybe(value) - ) - - # PyErr_SetString - @staticmethod - def set_string(type: PyObjectLike, message: StringLike) -> None: - return api_binding_base( - API_FUNCS["PyErr_SetString"], _deref_maybe(type), make_string(message) - ) - - # PyErr_SyntaxLocation - @staticmethod - def syntax_location(filename: StringLike, lineno: int) -> None: - return api_binding_base( - API_FUNCS["PyErr_SyntaxLocation"], make_string(filename), lineno - ) - - # PyErr_SyntaxLocationEx - @staticmethod - def syntax_location_ex(filename: StringLike, lineno: int, col_offset: int) -> None: - return api_binding_base( - API_FUNCS["PyErr_SyntaxLocationEx"], - make_string(filename), - lineno, - col_offset, - ) - - # PyErr_WarnEx - @staticmethod - def warn_ex(category: PyObjectLike, message: StringLike, stack_level: int) -> int: - return api_binding_base( - API_FUNCS["PyErr_WarnEx"], - _deref_maybe(category), - make_string(message), - stack_level, - ) - - # PyErr_WarnExplicit - @staticmethod - def warn_explicit( - category: PyObjectLike, - message: StringLike, - filename: StringLike, - lineno: int, - module: StringLike, - registry: PyObjectLike, - ) -> int: - return api_binding_base( - API_FUNCS["PyErr_WarnExplicit"], - _deref_maybe(category), - make_string(message), - make_string(filename), - lineno, - make_string(module), - _deref_maybe(registry), - ) - - # PyErr_WriteUnraisable - @staticmethod - def write_unraisable(obj: PyObjectLike) -> None: - return api_binding_base(API_FUNCS["PyErr_WriteUnraisable"], _deref_maybe(obj)) - - -class PyEval(_CallBase): - """Namespace containing API functions prefixed with `PyEval_`""" - - # PyEval_AcquireLock - @staticmethod - def acquire_lock() -> None: - return api_binding_base( - API_FUNCS["PyEval_AcquireLock"], - ) - - # PyEval_AcquireThread - @staticmethod - def acquire_thread(tstate: StructPointer[ThreadState]) -> None: - return api_binding_base(API_FUNCS["PyEval_AcquireThread"], tstate) - - # PyEval_EvalCode - @staticmethod - def eval_code( - co: PyObjectLike, globals: PyObjectLike, locals: PyObjectLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyEval_EvalCode"], - _deref_maybe(co), - _deref_maybe(globals), - _deref_maybe(locals), - ) - - # PyEval_EvalCodeEx - @staticmethod - def eval_code_ex( - co: PyObjectLike, - globals: PyObjectLike, - locals: PyObjectLike, - args: PointerLike, - argcount: int, - kws: PointerLike, - kwcount: int, - defs: PointerLike, - defcount: int, - kwdefs: PyObjectLike, - closure: PyObjectLike, - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyEval_EvalCodeEx"], - _deref_maybe(co), - _deref_maybe(globals), - _deref_maybe(locals), - args, - argcount, - kws, - kwcount, - defs, - defcount, - _deref_maybe(kwdefs), - _deref_maybe(closure), - ) - - # PyEval_EvalFrame - @staticmethod - def eval_frame(f: StructPointer[FrameObject]) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyEval_EvalFrame"], f) - - # PyEval_EvalFrameEx - @staticmethod - def eval_frame_ex(f: StructPointer[FrameObject], throwflag: int) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyEval_EvalFrameEx"], f, throwflag) - - # PyEval_GetBuiltins - @staticmethod - def get_builtins() -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyEval_GetBuiltins"], - ) - - # PyEval_GetFrame - @staticmethod - def get_frame() -> StructPointer[FrameObject]: - return api_binding_base( - API_FUNCS["PyEval_GetFrame"], - ) - - # PyEval_GetFuncDesc - @staticmethod - def get_func_desc(func: PyObjectLike) -> StringLike: - return api_binding_base(API_FUNCS["PyEval_GetFuncDesc"], _deref_maybe(func)) - - # PyEval_GetFuncName - @staticmethod - def get_func_name(func: PyObjectLike) -> StringLike: - return api_binding_base(API_FUNCS["PyEval_GetFuncName"], _deref_maybe(func)) - - # PyEval_GetGlobals - @staticmethod - def get_globals() -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyEval_GetGlobals"], - ) - - # PyEval_GetLocals - @staticmethod - def get_locals() -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyEval_GetLocals"], - ) - - # PyEval_InitThreads - @staticmethod - def init_threads() -> None: - return api_binding_base( - API_FUNCS["PyEval_InitThreads"], - ) - - # PyEval_ReleaseLock - @staticmethod - def release_lock() -> None: - return api_binding_base( - API_FUNCS["PyEval_ReleaseLock"], - ) - - # PyEval_ReleaseThread - @staticmethod - def release_thread(tstate: StructPointer[ThreadState]) -> None: - return api_binding_base(API_FUNCS["PyEval_ReleaseThread"], tstate) - - # PyEval_RestoreThread - @staticmethod - def restore_thread(tstate: StructPointer[ThreadState]) -> None: - return api_binding_base(API_FUNCS["PyEval_RestoreThread"], tstate) - - # PyEval_SaveThread - @staticmethod - def save_thread() -> StructPointer[ThreadState]: - return api_binding_base( - API_FUNCS["PyEval_SaveThread"], - ) - - # PyEval_ThreadsInitialized - @staticmethod - def threads_initialized() -> int: - return api_binding_base( - API_FUNCS["PyEval_ThreadsInitialized"], - ) - - # PyEval_MergeCompilerFlags - @staticmethod - def merge_compiler_flags() -> int: - return api_binding_base( - API_FUNCS["PyEval_MergeCompilerFlags"], - ) - - -class PyException(_CallBase): - """Namespace containing API functions prefixed with `PyException_`""" - - # PyException_GetCause - @staticmethod - def get_cause(ex: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyException_GetCause"], _deref_maybe(ex)) - - # PyException_GetContext - @staticmethod - def get_context(ex: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyException_GetContext"], _deref_maybe(ex)) - - # PyException_GetTraceback - @staticmethod - def get_traceback(ex: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyException_GetTraceback"], _deref_maybe(ex)) - - # PyException_SetCause - @staticmethod - def set_cause(ex: PyObjectLike, cause: PyObjectLike) -> None: - return api_binding_base( - API_FUNCS["PyException_SetCause"], _deref_maybe(ex), _deref_maybe(cause) - ) - - # PyException_SetContext - @staticmethod - def set_context(ex: PyObjectLike, ctx: PyObjectLike) -> None: - return api_binding_base( - API_FUNCS["PyException_SetContext"], _deref_maybe(ex), _deref_maybe(ctx) - ) - - # PyException_SetTraceback - @staticmethod - def set_traceback(ex: PyObjectLike, tb: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyException_SetTraceback"], _deref_maybe(ex), _deref_maybe(tb) - ) - - -class PyFile(_CallBase): - """Namespace containing API functions prefixed with `PyFile_`""" - - # PyFile_FromFd - @staticmethod - def from_fd( - fd: int, - name: StringLike, - mode: StringLike, - buffering: int, - encoding: StringLike, - errors: StringLike, - newline: StringLike, - closefd: int, - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyFile_FromFd"], - fd, - make_string(name), - make_string(mode), - buffering, - make_string(encoding), - make_string(errors), - make_string(newline), - closefd, - ) - - # PyFile_GetLine - @staticmethod - def get_line(p: PyObjectLike, n: int) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyFile_GetLine"], _deref_maybe(p), n) - - # PyFile_WriteObject - @staticmethod - def write_object(obj: PyObjectLike, p: PyObjectLike, flags: int) -> int: - return api_binding_base( - API_FUNCS["PyFile_WriteObject"], _deref_maybe(obj), _deref_maybe(p), flags - ) - - # PyFile_WriteString - @staticmethod - def write_string(s: StringLike, p: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyFile_WriteString"], make_string(s), _deref_maybe(p) - ) - - # PyFile_OpenCode - @staticmethod - def open_code(utf8path: StringLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyFile_OpenCode"], make_string(utf8path)) - - # PyFile_OpenCodeObject - @staticmethod - def open_code_object(path: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyFile_OpenCodeObject"], _deref_maybe(path)) - - # PyFile_SetOpenCodeHook - @staticmethod - def set_open_code_hook(hook: PointerLike) -> int: - return api_binding_base(API_FUNCS["PyFile_SetOpenCodeHook"], hook) - - -class PyFloat(_CallBase): - """Namespace containing API functions prefixed with `PyFloat_`""" - - # PyFloat_AsDouble - @staticmethod - def as_double(pyfloat: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyFloat_AsDouble"], _deref_maybe(pyfloat)) - - # PyFloat_FromDouble - @staticmethod - def from_double(v: int) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyFloat_FromDouble"], v) - - # PyFloat_FromString - @staticmethod - def from_string(str: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyFloat_FromString"], _deref_maybe(str)) - - # PyFloat_GetInfo - @staticmethod - def get_info() -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyFloat_GetInfo"], - ) - - # PyFloat_GetMax - @staticmethod - def get_max() -> int: - return api_binding_base( - API_FUNCS["PyFloat_GetMax"], - ) - - # PyFloat_GetMin - @staticmethod - def get_min() -> int: - return api_binding_base( - API_FUNCS["PyFloat_GetMin"], - ) - - -class PyFrame(_CallBase): - """Namespace containing API functions prefixed with `PyFrame_`""" - - # PyFrame_GetCode - @staticmethod - def get_code(frame: StructPointer[FrameObject]) -> StructPointer[CodeObject]: - return api_binding_base(API_FUNCS["PyFrame_GetCode"], frame) - - # PyFrame_GetLineNumber - @staticmethod - def get_line_number(frame: StructPointer[FrameObject]) -> int: - return api_binding_base(API_FUNCS["PyFrame_GetLineNumber"], frame) - - # PyFrame_LocalsToFast - @staticmethod - def locals_to_fast(f: StructPointer[FrameObject], i: int) -> None: - return api_binding_base(API_FUNCS["PyFrame_LocalsToFast"], f, i) - - # PyFrame_FastToLocalsWithError - @staticmethod - def fast_to_locals_with_error(f: StructPointer[FrameObject]) -> int: - return api_binding_base(API_FUNCS["PyFrame_FastToLocalsWithError"], f) - - # PyFrame_GetBack - @staticmethod - def get_back(frame: StructPointer[FrameObject]) -> StructPointer[FrameObject]: - return api_binding_base(API_FUNCS["PyFrame_GetBack"], frame) - - -class PyFrozenSet(_CallBase): - """Namespace containing API functions prefixed with `PyFrozenSet_`""" - - # PyFrozenSet_New - @staticmethod - def new(iterable: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyFrozenSet_New"], _deref_maybe(iterable)) - - -class PyGC(_CallBase): - """Namespace containing API functions prefixed with `PyGC_`""" - - # PyGC_Collect - @staticmethod - def collect() -> int: - return api_binding_base( - API_FUNCS["PyGC_Collect"], - ) - - # PyGC_Disable - @staticmethod - def disable() -> int: - return api_binding_base( - API_FUNCS["PyGC_Disable"], - ) - - # PyGC_Enable - @staticmethod - def enable() -> int: - return api_binding_base( - API_FUNCS["PyGC_Enable"], - ) - - # PyGC_IsEnabled - @staticmethod - def is_enabled() -> int: - return api_binding_base( - API_FUNCS["PyGC_IsEnabled"], - ) - - -class PyGILState(_CallBase): - """Namespace containing API functions prefixed with `PyGILState_`""" - - # PyGILState_Ensure - @staticmethod - def ensure() -> int: - return api_binding_base( - API_FUNCS["PyGILState_Ensure"], - ) - - # PyGILState_GetThisThreadState - @staticmethod - def get_this_thread_state() -> StructPointer[ThreadState]: - return api_binding_base( - API_FUNCS["PyGILState_GetThisThreadState"], - ) - - -class PyImport(_CallBase): - """Namespace containing API functions prefixed with `PyImport_`""" - - # PyImport_AddModule - @staticmethod - def add_module(name: StringLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyImport_AddModule"], make_string(name)) - - # PyImport_AddModuleObject - @staticmethod - def add_module_object(name: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyImport_AddModuleObject"], _deref_maybe(name) - ) - - # PyImport_ExecCodeModule - @staticmethod - def exec_code_module(name: StringLike, co: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyImport_ExecCodeModule"], make_string(name), _deref_maybe(co) - ) - - # PyImport_ExecCodeModuleEx - @staticmethod - def exec_code_module_ex( - name: StringLike, co: PyObjectLike, pathname: StringLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyImport_ExecCodeModuleEx"], - make_string(name), - _deref_maybe(co), - make_string(pathname), - ) - - # PyImport_ExecCodeModuleObject - @staticmethod - def exec_code_module_object( - name: PyObjectLike, - co: PyObjectLike, - pathname: PyObjectLike, - cpathname: PyObjectLike, - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyImport_ExecCodeModuleObject"], - _deref_maybe(name), - _deref_maybe(co), - _deref_maybe(pathname), - _deref_maybe(cpathname), - ) - - # PyImport_ExecCodeModuleWithPathnames - @staticmethod - def exec_code_module_with_pathnames( - name: StringLike, co: PyObjectLike, pathname: StringLike, cpathname: StringLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyImport_ExecCodeModuleWithPathnames"], - make_string(name), - _deref_maybe(co), - make_string(pathname), - make_string(cpathname), - ) - - # PyImport_GetImporter - @staticmethod - def get_importer(path: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyImport_GetImporter"], _deref_maybe(path)) - - # PyImport_GetMagicNumber - @staticmethod - def get_magic_number() -> int: - return api_binding_base( - API_FUNCS["PyImport_GetMagicNumber"], - ) - - # PyImport_GetMagicTag - @staticmethod - def get_magic_tag() -> StringLike: - return api_binding_base( - API_FUNCS["PyImport_GetMagicTag"], - ) - - # PyImport_GetModule - @staticmethod - def get_module(name: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyImport_GetModule"], _deref_maybe(name)) - - # PyImport_GetModuleDict - @staticmethod - def get_module_dict() -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyImport_GetModuleDict"], - ) - - # PyImport_Import - @staticmethod - def import_(name: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyImport_Import"], _deref_maybe(name)) - - # PyImport_ImportFrozenModule - @staticmethod - def import_frozen_module(name: StringLike) -> int: - return api_binding_base( - API_FUNCS["PyImport_ImportFrozenModule"], make_string(name) - ) - - # PyImport_ImportFrozenModuleObject - @staticmethod - def import_frozen_module_object(name: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyImport_ImportFrozenModuleObject"], _deref_maybe(name) - ) - - # PyImport_ImportModule - @staticmethod - def import_module(name: StringLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyImport_ImportModule"], make_string(name)) - - # PyImport_ImportModuleLevel - @staticmethod - def import_module_level( - name: StringLike, - globals: PyObjectLike, - locals: PyObjectLike, - fromlist: PyObjectLike, - level: int, - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyImport_ImportModuleLevel"], - make_string(name), - _deref_maybe(globals), - _deref_maybe(locals), - _deref_maybe(fromlist), - level, - ) - - # PyImport_ImportModuleLevelObject - @staticmethod - def import_module_level_object( - name: PyObjectLike, - globals: PyObjectLike, - locals: PyObjectLike, - fromlist: PyObjectLike, - level: int, - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyImport_ImportModuleLevelObject"], - _deref_maybe(name), - _deref_maybe(globals), - _deref_maybe(locals), - _deref_maybe(fromlist), - level, - ) - - # PyImport_ImportModuleNoBlock - @staticmethod - def import_module_no_block(name: StringLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyImport_ImportModuleNoBlock"], make_string(name) - ) - - # PyImport_ReloadModule - @staticmethod - def reload_module(m: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyImport_ReloadModule"], _deref_maybe(m)) - - -class PyIndex(_CallBase): - """Namespace containing API functions prefixed with `PyIndex_`""" - - # PyIndex_Check - @staticmethod - def check(o: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyIndex_Check"], _deref_maybe(o)) - - -class PyInterpreterState(_CallBase): - """Namespace containing API functions prefixed with `PyInterpreterState_`""" - - # PyInterpreterState_Clear - @staticmethod - def clear(interp: StructPointer[InterpreterState]) -> None: - return api_binding_base(API_FUNCS["PyInterpreterState_Clear"], interp) - - # PyInterpreterState_Delete - @staticmethod - def delete(interp: StructPointer[InterpreterState]) -> None: - return api_binding_base(API_FUNCS["PyInterpreterState_Delete"], interp) - - # PyInterpreterState_Get - @staticmethod - def get() -> StructPointer[InterpreterState]: - return api_binding_base( - API_FUNCS["PyInterpreterState_Get"], - ) - - # PyInterpreterState_GetDict - @staticmethod - def get_dict(interp: StructPointer[InterpreterState]) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyInterpreterState_GetDict"], interp) - - # PyInterpreterState_GetID - @staticmethod - def get_i_d(interp: StructPointer[InterpreterState]) -> int: - return api_binding_base(API_FUNCS["PyInterpreterState_GetID"], interp) - - # PyInterpreterState_New - @staticmethod - def new() -> StructPointer[InterpreterState]: - return api_binding_base( - API_FUNCS["PyInterpreterState_New"], - ) - - -class PyIter(_CallBase): - """Namespace containing API functions prefixed with `PyIter_`""" - - # PyIter_Check - @staticmethod - def check(o: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyIter_Check"], _deref_maybe(o)) - - # PyIter_Next - @staticmethod - def next(o: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyIter_Next"], _deref_maybe(o)) - - # PyIter_Send - @staticmethod - def send(iter: PyObjectLike, arg: PyObjectLike, presult: PointerLike) -> int: - return api_binding_base( - API_FUNCS["PyIter_Send"], _deref_maybe(iter), _deref_maybe(arg), presult - ) - - -class PyList(_CallBase): - """Namespace containing API functions prefixed with `PyList_`""" - - # PyList_Append - @staticmethod - def append(list: PyObjectLike, item: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyList_Append"], _deref_maybe(list), _deref_maybe(item) - ) - - # PyList_AsTuple - @staticmethod - def as_tuple(list: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyList_AsTuple"], _deref_maybe(list)) - - # PyList_GetItem - @staticmethod - def get_item(list: PyObjectLike, index: int) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyList_GetItem"], _deref_maybe(list), index) - - # PyList_GetSlice - @staticmethod - def get_slice(list: PyObjectLike, low: int, high: int) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyList_GetSlice"], _deref_maybe(list), low, high - ) - - # PyList_Insert - @staticmethod - def insert(list: PyObjectLike, index: int, item: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyList_Insert"], _deref_maybe(list), index, _deref_maybe(item) - ) - - # PyList_New - @staticmethod - def new(len: int) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyList_New"], len) - - # PyList_Reverse - @staticmethod - def reverse(list: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyList_Reverse"], _deref_maybe(list)) - - # PyList_SetItem - @staticmethod - def set_item(list: PyObjectLike, index: int, item: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyList_SetItem"], _deref_maybe(list), index, _deref_maybe(item) - ) - - # PyList_SetSlice - @staticmethod - def set_slice( - list: PyObjectLike, low: int, high: int, itemlist: PyObjectLike - ) -> int: - return api_binding_base( - API_FUNCS["PyList_SetSlice"], - _deref_maybe(list), - low, - high, - _deref_maybe(itemlist), - ) - - # PyList_Size - @staticmethod - def size(list: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyList_Size"], _deref_maybe(list)) - - # PyList_Sort - @staticmethod - def sort(list: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyList_Sort"], _deref_maybe(list)) - - -class PyLong(_CallBase): - """Namespace containing API functions prefixed with `PyLong_`""" - - # PyLong_AsDouble - @staticmethod - def as_double(pylong: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyLong_AsDouble"], _deref_maybe(pylong)) - - # PyLong_AsLong - @staticmethod - def as_long(obj: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyLong_AsLong"], _deref_maybe(obj)) - - # PyLong_AsLongAndOverflow - @staticmethod - def as_long_and_overflow(obj: PyObjectLike, overflow: PointerLike) -> int: - return api_binding_base( - API_FUNCS["PyLong_AsLongAndOverflow"], _deref_maybe(obj), overflow - ) - - # PyLong_AsLongLong - @staticmethod - def as_long_long(obj: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyLong_AsLongLong"], _deref_maybe(obj)) - - # PyLong_AsLongLongAndOverflow - @staticmethod - def as_long_long_and_overflow(obj: PyObjectLike, overflow: PointerLike) -> int: - return api_binding_base( - API_FUNCS["PyLong_AsLongLongAndOverflow"], _deref_maybe(obj), overflow - ) - - # PyLong_AsSize_t - @staticmethod - def as_size_t(pylong: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyLong_AsSize_t"], _deref_maybe(pylong)) - - # PyLong_AsSsize_t - @staticmethod - def as_ssize_t(pylong: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyLong_AsSsize_t"], _deref_maybe(pylong)) - - # PyLong_AsUnsignedLong - @staticmethod - def as_unsigned_long(pylong: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyLong_AsUnsignedLong"], _deref_maybe(pylong) - ) - - # PyLong_AsUnsignedLongLong - @staticmethod - def as_unsigned_long_long(pylong: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyLong_AsUnsignedLongLong"], _deref_maybe(pylong) - ) - - # PyLong_AsUnsignedLongLongMask - @staticmethod - def as_unsigned_long_long_mask(obj: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyLong_AsUnsignedLongLongMask"], _deref_maybe(obj) - ) - - # PyLong_AsUnsignedLongMask - @staticmethod - def as_unsigned_long_mask(obj: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyLong_AsUnsignedLongMask"], _deref_maybe(obj) - ) - - # PyLong_AsVoidPtr - @staticmethod - def as_void_ptr(pylong: PyObjectLike) -> PointerLike: - return api_binding_base(API_FUNCS["PyLong_AsVoidPtr"], _deref_maybe(pylong)) - - # PyLong_FromDouble - @staticmethod - def from_double(v: int) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyLong_FromDouble"], v) - - # PyLong_FromLong - @staticmethod - def from_long(v: int) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyLong_FromLong"], v) - - # PyLong_FromLongLong - @staticmethod - def from_long_long(v: int) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyLong_FromLongLong"], v) - - # PyLong_FromSize_t - @staticmethod - def from_size_t(v: int) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyLong_FromSize_t"], v) - - # PyLong_FromSsize_t - @staticmethod - def from_ssize_t(v: int) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyLong_FromSsize_t"], v) - - # PyLong_FromString - @staticmethod - def from_string(str: StringLike, pend: PointerLike, base: int) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyLong_FromString"], make_string(str), pend, base - ) - - # PyLong_FromUnsignedLong - @staticmethod - def from_unsigned_long(v: int) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyLong_FromUnsignedLong"], v) - - # PyLong_FromUnsignedLongLong - @staticmethod - def from_unsigned_long_long(v: int) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyLong_FromUnsignedLongLong"], v) - - # PyLong_FromVoidPtr - @staticmethod - def from_void_ptr(p: PointerLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyLong_FromVoidPtr"], p) - - -class PyMapping(_CallBase): - """Namespace containing API functions prefixed with `PyMapping_`""" - - # PyMapping_Check - @staticmethod - def check(o: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyMapping_Check"], _deref_maybe(o)) - - # PyMapping_GetItemString - @staticmethod - def get_item_string(o: PyObjectLike, key: StringLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyMapping_GetItemString"], _deref_maybe(o), make_string(key) - ) - - # PyMapping_HasKey - @staticmethod - def has_key(o: PyObjectLike, key: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyMapping_HasKey"], _deref_maybe(o), _deref_maybe(key) - ) - - # PyMapping_HasKeyString - @staticmethod - def has_key_string(o: PyObjectLike, key: StringLike) -> int: - return api_binding_base( - API_FUNCS["PyMapping_HasKeyString"], _deref_maybe(o), make_string(key) - ) - - # PyMapping_Items - @staticmethod - def items(o: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyMapping_Items"], _deref_maybe(o)) - - # PyMapping_Keys - @staticmethod - def keys(o: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyMapping_Keys"], _deref_maybe(o)) - - # PyMapping_Length - @staticmethod - def length(o: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyMapping_Length"], _deref_maybe(o)) - - # PyMapping_SetItemString - @staticmethod - def set_item_string(o: PyObjectLike, key: StringLike, v: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyMapping_SetItemString"], - _deref_maybe(o), - make_string(key), - _deref_maybe(v), - ) - - # PyMapping_Size - @staticmethod - def size(o: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyMapping_Size"], _deref_maybe(o)) - - # PyMapping_Values - @staticmethod - def values(o: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyMapping_Values"], _deref_maybe(o)) - - -class PyMem(_CallBase): - """Namespace containing API functions prefixed with `PyMem_`""" - - # PyMem_Calloc - @staticmethod - def calloc(nelem: int, elsize: int) -> PointerLike: - return api_binding_base(API_FUNCS["PyMem_Calloc"], nelem, elsize) - - # PyMem_Free - @staticmethod - def free(p: PointerLike) -> None: - return api_binding_base(API_FUNCS["PyMem_Free"], p) - - # PyMem_Malloc - @staticmethod - def malloc(n: int) -> PointerLike: - return api_binding_base(API_FUNCS["PyMem_Malloc"], n) - - # PyMem_Realloc - @staticmethod - def realloc(p: PointerLike, n: int) -> PointerLike: - return api_binding_base(API_FUNCS["PyMem_Realloc"], p, n) - - # PyMem_RawMalloc - @staticmethod - def raw_malloc(size: int) -> PointerLike: - return api_binding_base(API_FUNCS["PyMem_RawMalloc"], size) - - # PyMem_RawCalloc - @staticmethod - def raw_calloc(nelem: int, elsize: int) -> PointerLike: - return api_binding_base(API_FUNCS["PyMem_RawCalloc"], nelem, elsize) - - # PyMem_RawRealloc - @staticmethod - def raw_realloc(ptr: PointerLike, new_size: int) -> PointerLike: - return api_binding_base(API_FUNCS["PyMem_RawRealloc"], ptr, new_size) - - # PyMem_RawFree - @staticmethod - def raw_free(ptr: PointerLike) -> None: - return api_binding_base(API_FUNCS["PyMem_RawFree"], ptr) - - # PyMem_SetupDebugHooks - @staticmethod - def setup_debug_hooks() -> None: - return api_binding_base( - API_FUNCS["PyMem_SetupDebugHooks"], - ) - - -class PyMemoryView(_CallBase): - """Namespace containing API functions prefixed with `PyMemoryView_`""" - - # PyMemoryView_FromBuffer - @staticmethod - def from_buffer(view: StructPointer[Buffer]) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyMemoryView_FromBuffer"], view) - - # PyMemoryView_FromMemory - @staticmethod - def from_memory(mem: StringLike, size: int, flags: int) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyMemoryView_FromMemory"], make_string(mem), size, flags - ) - - # PyMemoryView_FromObject - @staticmethod - def from_object(obj: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyMemoryView_FromObject"], _deref_maybe(obj)) - - # PyMemoryView_GetContiguous - @staticmethod - def get_contiguous( - obj: PyObjectLike, buffertype: int, order: CharLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyMemoryView_GetContiguous"], - _deref_maybe(obj), - buffertype, - make_char(order), - ) - - -class PyModuleDef(_CallBase): - """Namespace containing API functions prefixed with `PyModuleDef_`""" - - # PyModuleDef_Init - @staticmethod - def init(df: StructPointer[ModuleDef]) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyModuleDef_Init"], df) - - -class PyModule(_CallBase): - """Namespace containing API functions prefixed with `PyModule_`""" - - # PyModule_AddFunctions - @staticmethod - def add_functions(module: PyObjectLike, functions: StructPointer[MethodDef]) -> int: - return api_binding_base( - API_FUNCS["PyModule_AddFunctions"], _deref_maybe(module), functions - ) - - # PyModule_AddIntConstant - @staticmethod - def add_int_constant(module: PyObjectLike, name: StringLike, value: int) -> int: - return api_binding_base( - API_FUNCS["PyModule_AddIntConstant"], - _deref_maybe(module), - make_string(name), - value, - ) - - # PyModule_AddObject - @staticmethod - def add_object(module: PyObjectLike, name: StringLike, value: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyModule_AddObject"], - _deref_maybe(module), - make_string(name), - _deref_maybe(value), - ) - - # PyModule_AddObjectRef - @staticmethod - def add_object_ref( - module: PyObjectLike, name: StringLike, value: PyObjectLike - ) -> int: - return api_binding_base( - API_FUNCS["PyModule_AddObjectRef"], - _deref_maybe(module), - make_string(name), - _deref_maybe(value), - ) - - # PyModule_AddStringConstant - @staticmethod - def add_string_constant( - module: PyObjectLike, name: StringLike, value: StringLike - ) -> int: - return api_binding_base( - API_FUNCS["PyModule_AddStringConstant"], - _deref_maybe(module), - make_string(name), - make_string(value), - ) - - # PyModule_AddType - @staticmethod - def add_type(module: PyObjectLike, type: StructPointer[TypeObject]) -> int: - return api_binding_base( - API_FUNCS["PyModule_AddType"], _deref_maybe(module), type - ) - - # PyModule_Create2 - @staticmethod - def create2(df: StructPointer[ModuleDef], module_api_version: int) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyModule_Create2"], df, module_api_version) - - # PyModule_ExecDef - @staticmethod - def exec_def(module: PyObjectLike, df: StructPointer[ModuleDef]) -> int: - return api_binding_base(API_FUNCS["PyModule_ExecDef"], _deref_maybe(module), df) - - # PyModule_FromDefAndSpec2 - @staticmethod - def from_def_and_spec2( - df: StructPointer[ModuleDef], spec: PyObjectLike, module_api_version: int - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyModule_FromDefAndSpec2"], - df, - _deref_maybe(spec), - module_api_version, - ) - - # PyModule_GetDef - @staticmethod - def get_def(module: PyObjectLike) -> StructPointer[ModuleDef]: - return api_binding_base(API_FUNCS["PyModule_GetDef"], _deref_maybe(module)) - - # PyModule_GetDict - @staticmethod - def get_dict(module: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyModule_GetDict"], _deref_maybe(module)) - - # PyModule_GetFilename - @staticmethod - def get_filename(module: PyObjectLike) -> StringLike: - return api_binding_base(API_FUNCS["PyModule_GetFilename"], _deref_maybe(module)) - - # PyModule_GetFilenameObject - @staticmethod - def get_filename_object(module: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyModule_GetFilenameObject"], _deref_maybe(module) - ) - - # PyModule_GetName - @staticmethod - def get_name(module: PyObjectLike) -> StringLike: - return api_binding_base(API_FUNCS["PyModule_GetName"], _deref_maybe(module)) - - # PyModule_GetNameObject - @staticmethod - def get_name_object(module: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyModule_GetNameObject"], _deref_maybe(module) - ) - - # PyModule_GetState - @staticmethod - def get_state(module: PyObjectLike) -> PointerLike: - return api_binding_base(API_FUNCS["PyModule_GetState"], _deref_maybe(module)) - - # PyModule_New - @staticmethod - def new(name: StringLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyModule_New"], make_string(name)) - - # PyModule_NewObject - @staticmethod - def new_object(name: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyModule_NewObject"], _deref_maybe(name)) - - # PyModule_SetDocString - @staticmethod - def set_doc_string(module: PyObjectLike, docstring: StringLike) -> int: - return api_binding_base( - API_FUNCS["PyModule_SetDocString"], - _deref_maybe(module), - make_string(docstring), - ) - - -class PyNumber(_CallBase): - """Namespace containing API functions prefixed with `PyNumber_`""" - - # PyNumber_Absolute - @staticmethod - def absolute(o: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyNumber_Absolute"], _deref_maybe(o)) - - # PyNumber_Add - @staticmethod - def add(o1: PyObjectLike, o2: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyNumber_Add"], _deref_maybe(o1), _deref_maybe(o2) - ) - - # PyNumber_And - @staticmethod - def and_(o1: PyObjectLike, o2: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyNumber_And"], _deref_maybe(o1), _deref_maybe(o2) - ) - - # PyNumber_AsSsize_t - @staticmethod - def as_ssize_t(o: PyObjectLike, exc: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyNumber_AsSsize_t"], _deref_maybe(o), _deref_maybe(exc) - ) - - # PyNumber_Check - @staticmethod - def check(o: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyNumber_Check"], _deref_maybe(o)) - - # PyNumber_Divmod - @staticmethod - def divmod(o1: PyObjectLike, o2: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyNumber_Divmod"], _deref_maybe(o1), _deref_maybe(o2) - ) - - # PyNumber_Float - @staticmethod - def float(o: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyNumber_Float"], _deref_maybe(o)) - - # PyNumber_FloorDivide - @staticmethod - def floor_divide(o1: PyObjectLike, o2: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyNumber_FloorDivide"], _deref_maybe(o1), _deref_maybe(o2) - ) - - # PyNumber_InPlaceAdd - @staticmethod - def in_place_add(o1: PyObjectLike, o2: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyNumber_InPlaceAdd"], _deref_maybe(o1), _deref_maybe(o2) - ) - - # PyNumber_InPlaceAnd - @staticmethod - def in_place_and(o1: PyObjectLike, o2: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyNumber_InPlaceAnd"], _deref_maybe(o1), _deref_maybe(o2) - ) - - # PyNumber_InPlaceFloorDivide - @staticmethod - def in_place_floor_divide(o1: PyObjectLike, o2: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyNumber_InPlaceFloorDivide"], _deref_maybe(o1), _deref_maybe(o2) - ) - - # PyNumber_InPlaceLshift - @staticmethod - def in_place_lshift(o1: PyObjectLike, o2: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyNumber_InPlaceLshift"], _deref_maybe(o1), _deref_maybe(o2) - ) - - # PyNumber_InPlaceMatrixMultiply - @staticmethod - def in_place_matrix_multiply(o1: PyObjectLike, o2: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyNumber_InPlaceMatrixMultiply"], - _deref_maybe(o1), - _deref_maybe(o2), - ) - - # PyNumber_InPlaceMultiply - @staticmethod - def in_place_multiply(o1: PyObjectLike, o2: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyNumber_InPlaceMultiply"], _deref_maybe(o1), _deref_maybe(o2) - ) - - # PyNumber_InPlaceOr - @staticmethod - def in_place_or(o1: PyObjectLike, o2: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyNumber_InPlaceOr"], _deref_maybe(o1), _deref_maybe(o2) - ) - - # PyNumber_InPlacePower - @staticmethod - def in_place_power( - o1: PyObjectLike, o2: PyObjectLike, o3: PyObjectLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyNumber_InPlacePower"], - _deref_maybe(o1), - _deref_maybe(o2), - _deref_maybe(o3), - ) - - # PyNumber_InPlaceRemainder - @staticmethod - def in_place_remainder(o1: PyObjectLike, o2: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyNumber_InPlaceRemainder"], _deref_maybe(o1), _deref_maybe(o2) - ) - - # PyNumber_InPlaceRshift - @staticmethod - def in_place_rshift(o1: PyObjectLike, o2: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyNumber_InPlaceRshift"], _deref_maybe(o1), _deref_maybe(o2) - ) - - # PyNumber_InPlaceSubtract - @staticmethod - def in_place_subtract(o1: PyObjectLike, o2: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyNumber_InPlaceSubtract"], _deref_maybe(o1), _deref_maybe(o2) - ) - - # PyNumber_InPlaceTrueDivide - @staticmethod - def in_place_true_divide(o1: PyObjectLike, o2: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyNumber_InPlaceTrueDivide"], _deref_maybe(o1), _deref_maybe(o2) - ) - - # PyNumber_InPlaceXor - @staticmethod - def in_place_xor(o1: PyObjectLike, o2: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyNumber_InPlaceXor"], _deref_maybe(o1), _deref_maybe(o2) - ) - - # PyNumber_Index - @staticmethod - def index(o: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyNumber_Index"], _deref_maybe(o)) - - # PyNumber_Invert - @staticmethod - def invert(o: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyNumber_Invert"], _deref_maybe(o)) - - # PyNumber_Long - @staticmethod - def long(o: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyNumber_Long"], _deref_maybe(o)) - - # PyNumber_Lshift - @staticmethod - def lshift(o1: PyObjectLike, o2: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyNumber_Lshift"], _deref_maybe(o1), _deref_maybe(o2) - ) - - # PyNumber_MatrixMultiply - @staticmethod - def matrix_multiply(o1: PyObjectLike, o2: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyNumber_MatrixMultiply"], _deref_maybe(o1), _deref_maybe(o2) - ) - - # PyNumber_Multiply - @staticmethod - def multiply(o1: PyObjectLike, o2: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyNumber_Multiply"], _deref_maybe(o1), _deref_maybe(o2) - ) - - # PyNumber_Negative - @staticmethod - def negative(o: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyNumber_Negative"], _deref_maybe(o)) - - # PyNumber_Or - @staticmethod - def or_(o1: PyObjectLike, o2: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyNumber_Or"], _deref_maybe(o1), _deref_maybe(o2) - ) - - # PyNumber_Positive - @staticmethod - def positive(o: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyNumber_Positive"], _deref_maybe(o)) - - # PyNumber_Power - @staticmethod - def power(o1: PyObjectLike, o2: PyObjectLike, o3: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyNumber_Power"], - _deref_maybe(o1), - _deref_maybe(o2), - _deref_maybe(o3), - ) - - # PyNumber_Remainder - @staticmethod - def remainder(o1: PyObjectLike, o2: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyNumber_Remainder"], _deref_maybe(o1), _deref_maybe(o2) - ) - - # PyNumber_Rshift - @staticmethod - def rshift(o1: PyObjectLike, o2: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyNumber_Rshift"], _deref_maybe(o1), _deref_maybe(o2) - ) - - # PyNumber_Subtract - @staticmethod - def subtract(o1: PyObjectLike, o2: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyNumber_Subtract"], _deref_maybe(o1), _deref_maybe(o2) - ) - - # PyNumber_ToBase - @staticmethod - def to_base(n: PyObjectLike, base: int) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyNumber_ToBase"], _deref_maybe(n), base) - - # PyNumber_TrueDivide - @staticmethod - def true_divide(o1: PyObjectLike, o2: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyNumber_TrueDivide"], _deref_maybe(o1), _deref_maybe(o2) - ) - - # PyNumber_Xor - @staticmethod - def xor(o1: PyObjectLike, o2: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyNumber_Xor"], _deref_maybe(o1), _deref_maybe(o2) - ) - - -class PyOS(_CallBase): - """Namespace containing API functions prefixed with `PyOS_`""" - - # PyOS_AfterFork - @staticmethod - def after_fork() -> None: - return api_binding_base( - API_FUNCS["PyOS_AfterFork"], - ) - - # PyOS_AfterFork_Child - @staticmethod - def after_fork_child() -> None: - return api_binding_base( - API_FUNCS["PyOS_AfterFork_Child"], - ) - - # PyOS_AfterFork_Parent - @staticmethod - def after_fork_parent() -> None: - return api_binding_base( - API_FUNCS["PyOS_AfterFork_Parent"], - ) - - # PyOS_BeforeFork - @staticmethod - def before_fork() -> None: - return api_binding_base( - API_FUNCS["PyOS_BeforeFork"], - ) - - # PyOS_FSPath - @staticmethod - def fs_path(path: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyOS_FSPath"], _deref_maybe(path)) - - # PyOS_double_to_string - @staticmethod - def double_to_string( - val: int, format_code: CharLike, precision: int, flags: int, ptype: PointerLike - ) -> StringLike: - return api_binding_base( - API_FUNCS["PyOS_double_to_string"], - val, - make_char(format_code), - precision, - flags, - ptype, - ) - - # PyOS_getsig - @staticmethod - def getsig(i: int) -> PointerLike: - return api_binding_base(API_FUNCS["PyOS_getsig"], i) - - # PyOS_setsig - @staticmethod - def setsig(i: int, h: PointerLike) -> PointerLike: - return api_binding_base(API_FUNCS["PyOS_setsig"], i, h) - - # PyOS_string_to_double - @staticmethod - def string_to_double( - s: StringLike, endptr: PointerLike, overflow_exception: PyObjectLike - ) -> int: - return api_binding_base( - API_FUNCS["PyOS_string_to_double"], - make_string(s), - endptr, - _deref_maybe(overflow_exception), - ) - - # PyOS_vsnprintf - @staticmethod - def vsnprintf( - str: StringLike, size: int, format: StringLike, va: PointerLike - ) -> int: - return api_binding_base( - API_FUNCS["PyOS_vsnprintf"], make_string(str), size, make_string(format), va - ) - - # PyOS_mystrnicmp - @staticmethod - def mystrnicmp(a: StringLike, b: StringLike, c: int) -> int: - return api_binding_base( - API_FUNCS["PyOS_mystrnicmp"], make_string(a), make_string(b), c - ) - - # PyOS_InterruptOccurred - @staticmethod - def interrupt_occurred() -> int: - return api_binding_base( - API_FUNCS["PyOS_InterruptOccurred"], - ) - - -class PyObject(_CallBase): - """Namespace containing API functions prefixed with `PyObject_`""" - - # PyObject_ASCII - @staticmethod - def ascii(o: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyObject_ASCII"], _deref_maybe(o)) - - # PyObject_AsCharBuffer - @staticmethod - def as_char_buffer( - obj: PyObjectLike, buffer: PointerLike, buffer_len: PointerLike - ) -> int: - return api_binding_base( - API_FUNCS["PyObject_AsCharBuffer"], _deref_maybe(obj), buffer, buffer_len - ) - - # PyObject_AsFileDescriptor - @staticmethod - def as_file_descriptor(p: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyObject_AsFileDescriptor"], _deref_maybe(p)) - - # PyObject_AsReadBuffer - @staticmethod - def as_read_buffer( - obj: PyObjectLike, buffer: PointerLike, buffer_len: PointerLike - ) -> int: - return api_binding_base( - API_FUNCS["PyObject_AsReadBuffer"], _deref_maybe(obj), buffer, buffer_len - ) - - # PyObject_AsWriteBuffer - @staticmethod - def as_write_buffer( - obj: PyObjectLike, buffer: PointerLike, buffer_len: PointerLike - ) -> int: - return api_binding_base( - API_FUNCS["PyObject_AsWriteBuffer"], _deref_maybe(obj), buffer, buffer_len - ) - - # PyObject_Bytes - @staticmethod - def bytes(o: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyObject_Bytes"], _deref_maybe(o)) - - # PyObject_Call - @staticmethod - def call( - callable: PyObjectLike, args: PyObjectLike, kwargs: PyObjectLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyObject_Call"], - _deref_maybe(callable), - _deref_maybe(args), - _deref_maybe(kwargs), - ) - - # PyObject_CallNoArgs - @staticmethod - def call_no_args(callable: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyObject_CallNoArgs"], _deref_maybe(callable) - ) - - # PyObject_CallObject - @staticmethod - def call_object(callable: PyObjectLike, args: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyObject_CallObject"], _deref_maybe(callable), _deref_maybe(args) - ) - - # PyObject_Calloc - @staticmethod - def calloc(nelem: int, elsize: int) -> PointerLike: - return api_binding_base(API_FUNCS["PyObject_Calloc"], nelem, elsize) - - # PyObject_CheckBuffer - @staticmethod - def check_buffer(obj: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyObject_CheckBuffer"], _deref_maybe(obj)) - - # PyObject_CheckReadBuffer - @staticmethod - def check_read_buffer(o: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyObject_CheckReadBuffer"], _deref_maybe(o)) - - # PyObject_CopyData - @staticmethod - def copy_data(dest: StructPointer[Buffer], src: StructPointer[Buffer]) -> int: - return api_binding_base(API_FUNCS["PyObject_CopyData"], dest, src) - - # PyObject_DelItem - @staticmethod - def del_item(o: PyObjectLike, key: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyObject_DelItem"], _deref_maybe(o), _deref_maybe(key) - ) - - # PyObject_Dir - @staticmethod - def dir(o: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyObject_Dir"], _deref_maybe(o)) - - # PyObject_Free - @staticmethod - def free(p: PointerLike) -> None: - return api_binding_base(API_FUNCS["PyObject_Free"], p) - - # PyObject_GC_Del - @staticmethod - def gc_del(op: PointerLike) -> None: - return api_binding_base(API_FUNCS["PyObject_GC_Del"], op) - - # PyObject_GC_IsFinalized - @staticmethod - def gc_is_finalized(op: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyObject_GC_IsFinalized"], _deref_maybe(op)) - - # PyObject_GC_IsTracked - @staticmethod - def gc_is_tracked(op: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyObject_GC_IsTracked"], _deref_maybe(op)) - - # PyObject_GC_Track - @staticmethod - def gc_track(op: PyObjectLike) -> None: - return api_binding_base(API_FUNCS["PyObject_GC_Track"], _deref_maybe(op)) - - # PyObject_GC_UnTrack - @staticmethod - def gc_untrack(op: PointerLike) -> None: - return api_binding_base(API_FUNCS["PyObject_GC_UnTrack"], op) - - # PyObject_GenericGetAttr - @staticmethod - def generic_get_attr(o: PyObjectLike, name: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyObject_GenericGetAttr"], _deref_maybe(o), _deref_maybe(name) - ) - - # PyObject_GenericGetDict - @staticmethod - def generic_get_dict(o: PyObjectLike, context: PointerLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyObject_GenericGetDict"], _deref_maybe(o), context - ) - - # PyObject_GenericSetAttr - @staticmethod - def generic_set_attr( - o: PyObjectLike, name: PyObjectLike, value: PyObjectLike - ) -> int: - return api_binding_base( - API_FUNCS["PyObject_GenericSetAttr"], - _deref_maybe(o), - _deref_maybe(name), - _deref_maybe(value), - ) - - # PyObject_GenericSetDict - @staticmethod - def generic_set_dict( - o: PyObjectLike, value: PyObjectLike, context: PointerLike - ) -> int: - return api_binding_base( - API_FUNCS["PyObject_GenericSetDict"], - _deref_maybe(o), - _deref_maybe(value), - context, - ) - - # PyObject_GetAIter - @staticmethod - def get_a_iter(o: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyObject_GetAIter"], _deref_maybe(o)) - - # PyObject_GetAttr - @staticmethod - def get_attr(o: PyObjectLike, attr_name: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyObject_GetAttr"], _deref_maybe(o), _deref_maybe(attr_name) - ) - - # PyObject_GetAttrString - @staticmethod - def get_attr_string(o: PyObjectLike, attr_name: StringLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyObject_GetAttrString"], _deref_maybe(o), make_string(attr_name) - ) - - # PyObject_GetBuffer - @staticmethod - def get_buffer( - exporter: PyObjectLike, view: StructPointer[Buffer], flags: int - ) -> int: - return api_binding_base( - API_FUNCS["PyObject_GetBuffer"], _deref_maybe(exporter), view, flags - ) - - # PyObject_GetItem - @staticmethod - def get_item(o: PyObjectLike, key: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyObject_GetItem"], _deref_maybe(o), _deref_maybe(key) - ) - - # PyObject_GetIter - @staticmethod - def get_iter(o: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyObject_GetIter"], _deref_maybe(o)) - - # PyObject_HasAttr - @staticmethod - def has_attr(o: PyObjectLike, attr_name: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyObject_HasAttr"], _deref_maybe(o), _deref_maybe(attr_name) - ) - - # PyObject_HasAttrString - @staticmethod - def has_attr_string(o: PyObjectLike, attr_name: StringLike) -> int: - return api_binding_base( - API_FUNCS["PyObject_HasAttrString"], _deref_maybe(o), make_string(attr_name) - ) - - # PyObject_Hash - @staticmethod - def hash(o: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyObject_Hash"], _deref_maybe(o)) - - # PyObject_HashNotImplemented - @staticmethod - def hash_not_implemented(o: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyObject_HashNotImplemented"], _deref_maybe(o) - ) - - # PyObject_Init - @staticmethod - def init(op: PyObjectLike, type: StructPointer[TypeObject]) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyObject_Init"], _deref_maybe(op), type) - - # PyObject_InitVar - @staticmethod - def init_var( - op: StructPointer[VarObject], type: StructPointer[TypeObject], size: int - ) -> StructPointer[VarObject]: - return api_binding_base(API_FUNCS["PyObject_InitVar"], op, type, size) - - # PyObject_IsInstance - @staticmethod - def is_instance(inst: PyObjectLike, cls: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyObject_IsInstance"], _deref_maybe(inst), _deref_maybe(cls) - ) - - # PyObject_IsSubclass - @staticmethod - def is_subclass(derived: PyObjectLike, cls: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyObject_IsSubclass"], _deref_maybe(derived), _deref_maybe(cls) - ) - - # PyObject_IsTrue - @staticmethod - def is_true(o: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyObject_IsTrue"], _deref_maybe(o)) - - # PyObject_Length - @staticmethod - def length(o: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyObject_Length"], _deref_maybe(o)) - - # PyObject_Malloc - @staticmethod - def malloc(n: int) -> PointerLike: - return api_binding_base(API_FUNCS["PyObject_Malloc"], n) - - # PyObject_Not - @staticmethod - def not_(o: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyObject_Not"], _deref_maybe(o)) - - # PyObject_Realloc - @staticmethod - def realloc(p: PointerLike, n: int) -> PointerLike: - return api_binding_base(API_FUNCS["PyObject_Realloc"], p, n) - - # PyObject_Repr - @staticmethod - def repr(o: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyObject_Repr"], _deref_maybe(o)) - - # PyObject_RichCompare - @staticmethod - def rich_compare(o1: PyObjectLike, o2: PyObjectLike, opid: int) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyObject_RichCompare"], _deref_maybe(o1), _deref_maybe(o2), opid - ) - - # PyObject_RichCompareBool - @staticmethod - def rich_compare_bool(o1: PyObjectLike, o2: PyObjectLike, opid: int) -> int: - return api_binding_base( - API_FUNCS["PyObject_RichCompareBool"], - _deref_maybe(o1), - _deref_maybe(o2), - opid, - ) - - # PyObject_SetAttr - @staticmethod - def set_attr(o: PyObjectLike, attr_name: PyObjectLike, v: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyObject_SetAttr"], - _deref_maybe(o), - _deref_maybe(attr_name), - _deref_maybe(v), - ) - - # PyObject_SetAttrString - @staticmethod - def set_attr_string(o: PyObjectLike, attr_name: StringLike, v: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyObject_SetAttrString"], - _deref_maybe(o), - make_string(attr_name), - _deref_maybe(v), - ) - - # PyObject_SetItem - @staticmethod - def set_item(o: PyObjectLike, key: PyObjectLike, v: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyObject_SetItem"], - _deref_maybe(o), - _deref_maybe(key), - _deref_maybe(v), - ) - - # PyObject_Size - @staticmethod - def size(o: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyObject_Size"], _deref_maybe(o)) - - # PyObject_Str - @staticmethod - def str(o: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyObject_Str"], _deref_maybe(o)) - - # PyObject_Type - @staticmethod - def type(o: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyObject_Type"], _deref_maybe(o)) - - # PyObject_GET_WEAKREFS_LISTPTR - @staticmethod - def get_weakrefs_listptr(op: PyObjectLike) -> PointerLike: - return api_binding_base( - API_FUNCS["PyObject_GET_WEAKREFS_LISTPTR"], _deref_maybe(op) - ) - - -class PySeqIter(_CallBase): - """Namespace containing API functions prefixed with `PySeqIter_`""" - - # PySeqIter_New - @staticmethod - def new(seq: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PySeqIter_New"], _deref_maybe(seq)) - - -class PySequence(_CallBase): - """Namespace containing API functions prefixed with `PySequence_`""" - - # PySequence_Check - @staticmethod - def check(o: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PySequence_Check"], _deref_maybe(o)) - - # PySequence_Concat - @staticmethod - def concat(o1: PyObjectLike, o2: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PySequence_Concat"], _deref_maybe(o1), _deref_maybe(o2) - ) - - # PySequence_Contains - @staticmethod - def contains(o: PyObjectLike, value: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PySequence_Contains"], _deref_maybe(o), _deref_maybe(value) - ) - - # PySequence_Count - @staticmethod - def count(o: PyObjectLike, value: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PySequence_Count"], _deref_maybe(o), _deref_maybe(value) - ) - - # PySequence_DelItem - @staticmethod - def del_item(o: PyObjectLike, i: int) -> int: - return api_binding_base(API_FUNCS["PySequence_DelItem"], _deref_maybe(o), i) - - # PySequence_DelSlice - @staticmethod - def del_slice(o: PyObjectLike, i1: int, i2: int) -> int: - return api_binding_base( - API_FUNCS["PySequence_DelSlice"], _deref_maybe(o), i1, i2 - ) - - # PySequence_Fast - @staticmethod - def fast(o: PyObjectLike, m: StringLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PySequence_Fast"], _deref_maybe(o), make_string(m) - ) - - # PySequence_GetItem - @staticmethod - def get_item(o: PyObjectLike, i: int) -> PyObjectLike: - return api_binding_base(API_FUNCS["PySequence_GetItem"], _deref_maybe(o), i) - - # PySequence_GetSlice - @staticmethod - def get_slice(o: PyObjectLike, i1: int, i2: int) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PySequence_GetSlice"], _deref_maybe(o), i1, i2 - ) - - # PySequence_InPlaceConcat - @staticmethod - def in_place_concat(o1: PyObjectLike, o2: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PySequence_InPlaceConcat"], _deref_maybe(o1), _deref_maybe(o2) - ) - - # PySequence_InPlaceRepeat - @staticmethod - def in_place_repeat(o: PyObjectLike, count: int) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PySequence_InPlaceRepeat"], _deref_maybe(o), count - ) - - # PySequence_Index - @staticmethod - def index(o: PyObjectLike, value: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PySequence_Index"], _deref_maybe(o), _deref_maybe(value) - ) - - # PySequence_Length - @staticmethod - def length(o: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PySequence_Length"], _deref_maybe(o)) - - # PySequence_List - @staticmethod - def list(o: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PySequence_List"], _deref_maybe(o)) - - # PySequence_Repeat - @staticmethod - def repeat(o: PyObjectLike, count: int) -> PyObjectLike: - return api_binding_base(API_FUNCS["PySequence_Repeat"], _deref_maybe(o), count) - - # PySequence_SetItem - @staticmethod - def set_item(o: PyObjectLike, i: int, v: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PySequence_SetItem"], _deref_maybe(o), i, _deref_maybe(v) - ) - - # PySequence_SetSlice - @staticmethod - def set_slice(o: PyObjectLike, i1: int, i2: int, v: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PySequence_SetSlice"], _deref_maybe(o), i1, i2, _deref_maybe(v) - ) - - # PySequence_Size - @staticmethod - def size(o: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PySequence_Size"], _deref_maybe(o)) - - # PySequence_Tuple - @staticmethod - def tuple(o: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PySequence_Tuple"], _deref_maybe(o)) - - -class PySet(_CallBase): - """Namespace containing API functions prefixed with `PySet_`""" - - # PySet_Add - @staticmethod - def add(set: PyObjectLike, key: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PySet_Add"], _deref_maybe(set), _deref_maybe(key) - ) - - # PySet_Clear - @staticmethod - def clear(set: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PySet_Clear"], _deref_maybe(set)) - - # PySet_Contains - @staticmethod - def contains(anyset: PyObjectLike, key: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PySet_Contains"], _deref_maybe(anyset), _deref_maybe(key) - ) - - # PySet_Discard - @staticmethod - def discard(set: PyObjectLike, key: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PySet_Discard"], _deref_maybe(set), _deref_maybe(key) - ) - - # PySet_New - @staticmethod - def new(iterable: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PySet_New"], _deref_maybe(iterable)) - - # PySet_Pop - @staticmethod - def pop(set: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PySet_Pop"], _deref_maybe(set)) - - # PySet_Size - @staticmethod - def size(anyset: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PySet_Size"], _deref_maybe(anyset)) - - -class PySlice(_CallBase): - """Namespace containing API functions prefixed with `PySlice_`""" - - # PySlice_AdjustIndices - @staticmethod - def adjust_indices( - length: int, start: PointerLike, stop: PointerLike, step: int - ) -> int: - return api_binding_base( - API_FUNCS["PySlice_AdjustIndices"], length, start, stop, step - ) - - # PySlice_GetIndices - @staticmethod - def get_indices( - slice: PyObjectLike, - length: int, - start: PointerLike, - stop: PointerLike, - step: PointerLike, - ) -> int: - return api_binding_base( - API_FUNCS["PySlice_GetIndices"], - _deref_maybe(slice), - length, - start, - stop, - step, - ) - - # PySlice_GetIndicesEx - @staticmethod - def get_indices_ex( - slice: PyObjectLike, - length: int, - start: PointerLike, - stop: PointerLike, - step: PointerLike, - slicelength: PointerLike, - ) -> int: - return api_binding_base( - API_FUNCS["PySlice_GetIndicesEx"], - _deref_maybe(slice), - length, - start, - stop, - step, - slicelength, - ) - - # PySlice_New - @staticmethod - def new( - start: PyObjectLike, stop: PyObjectLike, step: PyObjectLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PySlice_New"], - _deref_maybe(start), - _deref_maybe(stop), - _deref_maybe(step), - ) - - # PySlice_Unpack - @staticmethod - def unpack( - slice: PyObjectLike, start: PointerLike, stop: PointerLike, step: PointerLike - ) -> int: - return api_binding_base( - API_FUNCS["PySlice_Unpack"], _deref_maybe(slice), start, stop, step - ) - - -class PyState(_CallBase): - """Namespace containing API functions prefixed with `PyState_`""" - - # PyState_AddModule - @staticmethod - def add_module(module: PyObjectLike, df: StructPointer[ModuleDef]) -> int: - return api_binding_base( - API_FUNCS["PyState_AddModule"], _deref_maybe(module), df - ) - - # PyState_FindModule - @staticmethod - def find_module(df: StructPointer[ModuleDef]) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyState_FindModule"], df) - - # PyState_RemoveModule - @staticmethod - def remove_module(df: StructPointer[ModuleDef]) -> int: - return api_binding_base(API_FUNCS["PyState_RemoveModule"], df) - - -class PyStructSequence(_CallBase): - """Namespace containing API functions prefixed with `PyStructSequence_`""" - - # PyStructSequence_GetItem - @staticmethod - def get_item(p: PyObjectLike, pos: int) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyStructSequence_GetItem"], _deref_maybe(p), pos - ) - - # PyStructSequence_New - @staticmethod - def new(type: StructPointer[TypeObject]) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyStructSequence_New"], type) - - # PyStructSequence_NewType - @staticmethod - def new_type() -> StructPointer[TypeObject]: - return api_binding_base( - API_FUNCS["PyStructSequence_NewType"], - ) - - # PyStructSequence_SetItem - @staticmethod - def set_item(p: PyObjectLike, pos: int, o: PyObjectLike) -> None: - return api_binding_base( - API_FUNCS["PyStructSequence_SetItem"], _deref_maybe(p), pos, _deref_maybe(o) - ) - - -class PySys(_CallBase): - """Namespace containing API functions prefixed with `PySys_`""" - - # PySys_AddWarnOption - @staticmethod - def add_warn_option(s: str) -> None: - return api_binding_base(API_FUNCS["PySys_AddWarnOption"], s) - - # PySys_AddWarnOptionUnicode - @staticmethod - def add_warn_option_unicode(unicode: PyObjectLike) -> None: - return api_binding_base( - API_FUNCS["PySys_AddWarnOptionUnicode"], _deref_maybe(unicode) - ) - - # PySys_AddXOption - @staticmethod - def add_x_option(s: str) -> None: - return api_binding_base(API_FUNCS["PySys_AddXOption"], s) - - # PySys_GetObject - @staticmethod - def get_object(name: StringLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PySys_GetObject"], make_string(name)) - - # PySys_GetXOptions - @staticmethod - def get_x_options() -> PyObjectLike: - return api_binding_base( - API_FUNCS["PySys_GetXOptions"], - ) - - # PySys_ResetWarnOptions - @staticmethod - def reset_warn_options() -> None: - return api_binding_base( - API_FUNCS["PySys_ResetWarnOptions"], - ) - - # PySys_SetArgv - @staticmethod - def set_argv(argc: int, argv: PointerLike) -> None: - return api_binding_base(API_FUNCS["PySys_SetArgv"], argc, argv) - - # PySys_SetArgvEx - @staticmethod - def set_argv_ex(argc: int, argv: PointerLike, updatepath: int) -> None: - return api_binding_base(API_FUNCS["PySys_SetArgvEx"], argc, argv, updatepath) - - # PySys_SetObject - @staticmethod - def set_object(name: StringLike, v: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PySys_SetObject"], make_string(name), _deref_maybe(v) - ) - - # PySys_SetPath - @staticmethod - def set_path(path: str) -> None: - return api_binding_base(API_FUNCS["PySys_SetPath"], path) - - -class PyThreadState(_CallBase): - """Namespace containing API functions prefixed with `PyThreadState_`""" - - # PyThreadState_Clear - @staticmethod - def clear(tstate: StructPointer[ThreadState]) -> None: - return api_binding_base(API_FUNCS["PyThreadState_Clear"], tstate) - - # PyThreadState_Delete - @staticmethod - def delete(tstate: StructPointer[ThreadState]) -> None: - return api_binding_base(API_FUNCS["PyThreadState_Delete"], tstate) - - # PyThreadState_Get - @staticmethod - def get() -> StructPointer[ThreadState]: - return api_binding_base( - API_FUNCS["PyThreadState_Get"], - ) - - # PyThreadState_GetDict - @staticmethod - def get_dict() -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyThreadState_GetDict"], - ) - - # PyThreadState_GetFrame - @staticmethod - def get_frame(tstate: StructPointer[ThreadState]) -> StructPointer[FrameObject]: - return api_binding_base(API_FUNCS["PyThreadState_GetFrame"], tstate) - - # PyThreadState_GetID - @staticmethod - def get_i_d(tstate: StructPointer[ThreadState]) -> int: - return api_binding_base(API_FUNCS["PyThreadState_GetID"], tstate) - - # PyThreadState_GetInterpreter - @staticmethod - def get_interpreter( - tstate: StructPointer[ThreadState], - ) -> StructPointer[InterpreterState]: - return api_binding_base(API_FUNCS["PyThreadState_GetInterpreter"], tstate) - - # PyThreadState_New - @staticmethod - def new(interp: StructPointer[InterpreterState]) -> StructPointer[ThreadState]: - return api_binding_base(API_FUNCS["PyThreadState_New"], interp) - - # PyThreadState_SetAsyncExc - @staticmethod - def set_async_exc(id: int, exc: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyThreadState_SetAsyncExc"], id, _deref_maybe(exc) - ) - - # PyThreadState_Swap - @staticmethod - def swap(tstate: StructPointer[ThreadState]) -> StructPointer[ThreadState]: - return api_binding_base(API_FUNCS["PyThreadState_Swap"], tstate) - - -class PyThread(_CallBase): - """Namespace containing API functions prefixed with `PyThread_`""" - - # PyThread_ReInitTLS - @staticmethod - def re_init_t_l_s() -> None: - return api_binding_base( - API_FUNCS["PyThread_ReInitTLS"], - ) - - # PyThread_create_key - @staticmethod - def create_key() -> int: - return api_binding_base( - API_FUNCS["PyThread_create_key"], - ) - - # PyThread_delete_key - @staticmethod - def delete_key(key: int) -> None: - return api_binding_base(API_FUNCS["PyThread_delete_key"], key) - - # PyThread_delete_key_value - @staticmethod - def delete_key_value(key: int) -> None: - return api_binding_base(API_FUNCS["PyThread_delete_key_value"], key) - - # PyThread_get_key_value - @staticmethod - def get_key_value(key: int) -> PointerLike: - return api_binding_base(API_FUNCS["PyThread_get_key_value"], key) - - # PyThread_set_key_value - @staticmethod - def set_key_value(key: int, value: PointerLike) -> int: - return api_binding_base(API_FUNCS["PyThread_set_key_value"], key, value) - - # PyThread_tss_alloc - @staticmethod - def tss_alloc() -> StructPointer[TssT]: - return api_binding_base( - API_FUNCS["PyThread_tss_alloc"], - ) - - # PyThread_tss_create - @staticmethod - def tss_create(key: StructPointer[TssT]) -> int: - return api_binding_base(API_FUNCS["PyThread_tss_create"], key) - - # PyThread_tss_delete - @staticmethod - def tss_delete(key: StructPointer[TssT]) -> None: - return api_binding_base(API_FUNCS["PyThread_tss_delete"], key) - - # PyThread_tss_free - @staticmethod - def tss_free(key: StructPointer[TssT]) -> None: - return api_binding_base(API_FUNCS["PyThread_tss_free"], key) - - # PyThread_tss_get - @staticmethod - def tss_get(key: StructPointer[TssT]) -> PointerLike: - return api_binding_base(API_FUNCS["PyThread_tss_get"], key) - - # PyThread_tss_is_created - @staticmethod - def tss_is_created(key: StructPointer[TssT]) -> int: - return api_binding_base(API_FUNCS["PyThread_tss_is_created"], key) - - # PyThread_tss_set - @staticmethod - def tss_set(key: StructPointer[TssT], value: PointerLike) -> int: - return api_binding_base(API_FUNCS["PyThread_tss_set"], key, value) - - -class PyTuple(_CallBase): - """Namespace containing API functions prefixed with `PyTuple_`""" - - # PyTuple_GetItem - @staticmethod - def get_item(p: PyObjectLike, pos: int) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyTuple_GetItem"], _deref_maybe(p), pos) - - # PyTuple_GetSlice - @staticmethod - def get_slice(p: PyObjectLike, low: int, high: int) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyTuple_GetSlice"], _deref_maybe(p), low, high - ) - - # PyTuple_New - @staticmethod - def new(len: int) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyTuple_New"], len) - - # PyTuple_SetItem - @staticmethod - def set_item(p: PyObjectLike, pos: int, o: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyTuple_SetItem"], _deref_maybe(p), pos, _deref_maybe(o) - ) - - # PyTuple_Size - @staticmethod - def size(p: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyTuple_Size"], _deref_maybe(p)) - - -class PyType(_CallBase): - """Namespace containing API functions prefixed with `PyType_`""" - - # PyType_ClearCache - @staticmethod - def clear_cache() -> int: - return api_binding_base( - API_FUNCS["PyType_ClearCache"], - ) - - # PyType_FromModuleAndSpec - @staticmethod - def from_module_and_spec( - module: PyObjectLike, spec: StructPointer[PyTypeSpec], bases: PyObjectLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyType_FromModuleAndSpec"], - _deref_maybe(module), - spec, - _deref_maybe(bases), - ) - - # PyType_FromSpec - @staticmethod - def from_spec(spec: StructPointer[PyTypeSpec]) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyType_FromSpec"], spec) - - # PyType_FromSpecWithBases - @staticmethod - def from_spec_with_bases( - spec: StructPointer[PyTypeSpec], bases: PyObjectLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyType_FromSpecWithBases"], spec, _deref_maybe(bases) - ) - - # PyType_GenericAlloc - @staticmethod - def generic_alloc(type: StructPointer[TypeObject], nitems: int) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyType_GenericAlloc"], type, nitems) - - # PyType_GenericNew - @staticmethod - def generic_new( - type: StructPointer[TypeObject], args: PyObjectLike, kwds: PyObjectLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyType_GenericNew"], type, _deref_maybe(args), _deref_maybe(kwds) - ) - - # PyType_GetFlags - @staticmethod - def get_flags(type: StructPointer[TypeObject]) -> int: - return api_binding_base(API_FUNCS["PyType_GetFlags"], type) - - # PyType_GetModule - @staticmethod - def get_module(type: StructPointer[TypeObject]) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyType_GetModule"], type) - - # PyType_GetModuleState - @staticmethod - def get_module_state(type: StructPointer[TypeObject]) -> PointerLike: - return api_binding_base(API_FUNCS["PyType_GetModuleState"], type) - - # PyType_GetSlot - @staticmethod - def get_slot(type: StructPointer[TypeObject], slot: int) -> PointerLike: - return api_binding_base(API_FUNCS["PyType_GetSlot"], type, slot) - - # PyType_IsSubtype - @staticmethod - def is_subtype(a: StructPointer[TypeObject], b: StructPointer[TypeObject]) -> int: - return api_binding_base(API_FUNCS["PyType_IsSubtype"], a, b) - - # PyType_Modified - @staticmethod - def modified(type: StructPointer[TypeObject]) -> None: - return api_binding_base(API_FUNCS["PyType_Modified"], type) - - # PyType_Ready - @staticmethod - def ready(type: StructPointer[TypeObject]) -> int: - return api_binding_base(API_FUNCS["PyType_Ready"], type) - - -class PyUnicodeDecodeError(_CallBase): - """Namespace containing API functions prefixed with `PyUnicodeDecodeError_`""" - - # PyUnicodeDecodeError_Create - @staticmethod - def create( - encoding: StringLike, - object: StringLike, - length: int, - start: int, - end: int, - reason: StringLike, - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicodeDecodeError_Create"], - make_string(encoding), - make_string(object), - length, - start, - end, - make_string(reason), - ) - - # PyUnicodeDecodeError_GetEncoding - @staticmethod - def get_encoding(exc: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicodeDecodeError_GetEncoding"], _deref_maybe(exc) - ) - - # PyUnicodeDecodeError_GetEnd - @staticmethod - def get_end(exc: PyObjectLike, end: PointerLike) -> int: - return api_binding_base( - API_FUNCS["PyUnicodeDecodeError_GetEnd"], _deref_maybe(exc), end - ) - - # PyUnicodeDecodeError_GetObject - @staticmethod - def get_object(exc: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicodeDecodeError_GetObject"], _deref_maybe(exc) - ) - - # PyUnicodeDecodeError_GetReason - @staticmethod - def get_reason(exc: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicodeDecodeError_GetReason"], _deref_maybe(exc) - ) - - # PyUnicodeDecodeError_GetStart - @staticmethod - def get_start(exc: PyObjectLike, start: PointerLike) -> int: - return api_binding_base( - API_FUNCS["PyUnicodeDecodeError_GetStart"], _deref_maybe(exc), start - ) - - # PyUnicodeDecodeError_SetEnd - @staticmethod - def set_end(exc: PyObjectLike, end: int) -> int: - return api_binding_base( - API_FUNCS["PyUnicodeDecodeError_SetEnd"], _deref_maybe(exc), end - ) - - # PyUnicodeDecodeError_SetReason - @staticmethod - def set_reason(exc: PyObjectLike, reason: StringLike) -> int: - return api_binding_base( - API_FUNCS["PyUnicodeDecodeError_SetReason"], - _deref_maybe(exc), - make_string(reason), - ) - - # PyUnicodeDecodeError_SetStart - @staticmethod - def set_start(exc: PyObjectLike, start: int) -> int: - return api_binding_base( - API_FUNCS["PyUnicodeDecodeError_SetStart"], _deref_maybe(exc), start - ) - - -class PyUnicodeEncodeError(_CallBase): - """Namespace containing API functions prefixed with `PyUnicodeEncodeError_`""" - - # PyUnicodeEncodeError_GetEncoding - @staticmethod - def get_encoding(exc: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicodeEncodeError_GetEncoding"], _deref_maybe(exc) - ) - - # PyUnicodeEncodeError_GetEnd - @staticmethod - def get_end(exc: PyObjectLike, end: PointerLike) -> int: - return api_binding_base( - API_FUNCS["PyUnicodeEncodeError_GetEnd"], _deref_maybe(exc), end - ) - - # PyUnicodeEncodeError_GetObject - @staticmethod - def get_object(exc: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicodeEncodeError_GetObject"], _deref_maybe(exc) - ) - - # PyUnicodeEncodeError_GetReason - @staticmethod - def get_reason(exc: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicodeEncodeError_GetReason"], _deref_maybe(exc) - ) - - # PyUnicodeEncodeError_GetStart - @staticmethod - def get_start(exc: PyObjectLike, start: PointerLike) -> int: - return api_binding_base( - API_FUNCS["PyUnicodeEncodeError_GetStart"], _deref_maybe(exc), start - ) - - # PyUnicodeEncodeError_SetEnd - @staticmethod - def set_end(exc: PyObjectLike, end: int) -> int: - return api_binding_base( - API_FUNCS["PyUnicodeEncodeError_SetEnd"], _deref_maybe(exc), end - ) - - # PyUnicodeEncodeError_SetReason - @staticmethod - def set_reason(exc: PyObjectLike, reason: StringLike) -> int: - return api_binding_base( - API_FUNCS["PyUnicodeEncodeError_SetReason"], - _deref_maybe(exc), - make_string(reason), - ) - - # PyUnicodeEncodeError_SetStart - @staticmethod - def set_start(exc: PyObjectLike, start: int) -> int: - return api_binding_base( - API_FUNCS["PyUnicodeEncodeError_SetStart"], _deref_maybe(exc), start - ) - - -class PyUnicodeTranslateError(_CallBase): - """Namespace containing API functions prefixed with `PyUnicodeTranslateError_`""" - - # PyUnicodeTranslateError_GetEnd - @staticmethod - def get_end(exc: PyObjectLike, end: PointerLike) -> int: - return api_binding_base( - API_FUNCS["PyUnicodeTranslateError_GetEnd"], _deref_maybe(exc), end - ) - - # PyUnicodeTranslateError_GetObject - @staticmethod - def get_object(exc: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicodeTranslateError_GetObject"], _deref_maybe(exc) - ) - - # PyUnicodeTranslateError_GetReason - @staticmethod - def get_reason(exc: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicodeTranslateError_GetReason"], _deref_maybe(exc) - ) - - # PyUnicodeTranslateError_GetStart - @staticmethod - def get_start(exc: PyObjectLike, start: PointerLike) -> int: - return api_binding_base( - API_FUNCS["PyUnicodeTranslateError_GetStart"], _deref_maybe(exc), start - ) - - # PyUnicodeTranslateError_SetEnd - @staticmethod - def set_end(exc: PyObjectLike, end: int) -> int: - return api_binding_base( - API_FUNCS["PyUnicodeTranslateError_SetEnd"], _deref_maybe(exc), end - ) - - # PyUnicodeTranslateError_SetReason - @staticmethod - def set_reason(exc: PyObjectLike, reason: StringLike) -> int: - return api_binding_base( - API_FUNCS["PyUnicodeTranslateError_SetReason"], - _deref_maybe(exc), - make_string(reason), - ) - - # PyUnicodeTranslateError_SetStart - @staticmethod - def set_start(exc: PyObjectLike, start: int) -> int: - return api_binding_base( - API_FUNCS["PyUnicodeTranslateError_SetStart"], _deref_maybe(exc), start - ) - - -class PyUnicode(_CallBase): - """Namespace containing API functions prefixed with `PyUnicode_`""" - - # PyUnicode_AsASCIIString - @staticmethod - def as_ascii_string(unicode: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_AsASCIIString"], _deref_maybe(unicode) - ) - - # PyUnicode_AsCharmapString - @staticmethod - def as_charmap_string(unicode: PyObjectLike, mapping: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_AsCharmapString"], - _deref_maybe(unicode), - _deref_maybe(mapping), - ) - - # PyUnicode_AsEncodedString - @staticmethod - def as_encoded_string( - unicode: PyObjectLike, encoding: StringLike, errors: StringLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_AsEncodedString"], - _deref_maybe(unicode), - make_string(encoding), - make_string(errors), - ) - - # PyUnicode_AsLatin1String - @staticmethod - def as_latin1_string(unicode: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_AsLatin1String"], _deref_maybe(unicode) - ) - - # PyUnicode_AsRawUnicodeEscapeString - @staticmethod - def as_raw_unicode_escape_string(unicode: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_AsRawUnicodeEscapeString"], _deref_maybe(unicode) - ) - - # PyUnicode_AsUCS4 - @staticmethod - def as_ucs_4( - u: PyObjectLike, buffer: PointerLike, buflen: int, copy_null: int - ) -> PointerLike: - return api_binding_base( - API_FUNCS["PyUnicode_AsUCS4"], _deref_maybe(u), buffer, buflen, copy_null - ) - - # PyUnicode_AsUCS4Copy - @staticmethod - def as_ucs_4_copy(u: PyObjectLike) -> PointerLike: - return api_binding_base(API_FUNCS["PyUnicode_AsUCS4Copy"], _deref_maybe(u)) - - # PyUnicode_AsUTF16String - @staticmethod - def as_utf_16_string(unicode: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_AsUTF16String"], _deref_maybe(unicode) - ) - - # PyUnicode_AsUTF32String - @staticmethod - def as_utf_32_string(unicode: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_AsUTF32String"], _deref_maybe(unicode) - ) - - # PyUnicode_AsUTF8AndSize - @staticmethod - def as_utf_8_and_size(unicode: PyObjectLike, size: PointerLike) -> StringLike: - return api_binding_base( - API_FUNCS["PyUnicode_AsUTF8AndSize"], _deref_maybe(unicode), size - ) - - # PyUnicode_AsUTF8String - @staticmethod - def as_utf_8_string(unicode: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_AsUTF8String"], _deref_maybe(unicode) - ) - - # PyUnicode_AsUnicodeEscapeString - @staticmethod - def as_unicode_escape_string(unicode: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_AsUnicodeEscapeString"], _deref_maybe(unicode) - ) - - # PyUnicode_AsWideChar - @staticmethod - def as_wide_char(unicode: PyObjectLike, w: str, size: int) -> int: - return api_binding_base( - API_FUNCS["PyUnicode_AsWideChar"], _deref_maybe(unicode), w, size - ) - - # PyUnicode_AsWideCharString - @staticmethod - def as_wide_char_string(unicode: PyObjectLike, size: PointerLike) -> str: - return api_binding_base( - API_FUNCS["PyUnicode_AsWideCharString"], _deref_maybe(unicode), size - ) - - # PyUnicode_Compare - @staticmethod - def compare(left: PyObjectLike, right: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyUnicode_Compare"], _deref_maybe(left), _deref_maybe(right) - ) - - # PyUnicode_CompareWithASCIIString - @staticmethod - def compare_with_ascii_string(uni: PyObjectLike, string: StringLike) -> int: - return api_binding_base( - API_FUNCS["PyUnicode_CompareWithASCIIString"], - _deref_maybe(uni), - make_string(string), - ) - - # PyUnicode_Concat - @staticmethod - def concat(left: PyObjectLike, right: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_Concat"], _deref_maybe(left), _deref_maybe(right) - ) - - # PyUnicode_Contains - @staticmethod - def contains(container: PyObjectLike, element: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["PyUnicode_Contains"], - _deref_maybe(container), - _deref_maybe(element), - ) - - # PyUnicode_Count - @staticmethod - def count(str: PyObjectLike, substr: PyObjectLike, start: int, end: int) -> int: - return api_binding_base( - API_FUNCS["PyUnicode_Count"], - _deref_maybe(str), - _deref_maybe(substr), - start, - end, - ) - - # PyUnicode_Decode - @staticmethod - def decode( - s: StringLike, size: int, encoding: StringLike, errors: StringLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_Decode"], - make_string(s), - size, - make_string(encoding), - make_string(errors), - ) - - # PyUnicode_DecodeASCII - @staticmethod - def decode_ascii(s: StringLike, size: int, errors: StringLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_DecodeASCII"], - make_string(s), - size, - make_string(errors), - ) - - # PyUnicode_DecodeCharmap - @staticmethod - def decode_charmap( - data: StringLike, size: int, mapping: PyObjectLike, errors: StringLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_DecodeCharmap"], - make_string(data), - size, - _deref_maybe(mapping), - make_string(errors), - ) - - # PyUnicode_DecodeFSDefault - @staticmethod - def decode_fsdefault(s: StringLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyUnicode_DecodeFSDefault"], make_string(s)) - - # PyUnicode_DecodeFSDefaultAndSize - @staticmethod - def decode_fs_default_and_size(s: StringLike, size: int) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_DecodeFSDefaultAndSize"], make_string(s), size - ) - - # PyUnicode_DecodeLatin1 - @staticmethod - def decode_latin1(s: StringLike, size: int, errors: StringLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_DecodeLatin1"], - make_string(s), - size, - make_string(errors), - ) - - # PyUnicode_DecodeLocale - @staticmethod - def decode_locale(str: StringLike, errors: StringLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_DecodeLocale"], make_string(str), make_string(errors) - ) - - # PyUnicode_DecodeLocaleAndSize - @staticmethod - def decode_locale_and_size( - str: StringLike, len: int, errors: StringLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_DecodeLocaleAndSize"], - make_string(str), - len, - make_string(errors), - ) - - # PyUnicode_DecodeRawUnicodeEscape - @staticmethod - def decode_raw_unicode_escape( - s: StringLike, size: int, errors: StringLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_DecodeRawUnicodeEscape"], - make_string(s), - size, - make_string(errors), - ) - - # PyUnicode_DecodeUTF16 - @staticmethod - def decode_utf_16( - s: StringLike, size: int, errors: StringLike, byteorder: PointerLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_DecodeUTF16"], - make_string(s), - size, - make_string(errors), - byteorder, - ) - - # PyUnicode_DecodeUTF16Stateful - @staticmethod - def decode_utf_16_stateful( - s: StringLike, - size: int, - errors: StringLike, - byteorder: PointerLike, - consumed: PointerLike, - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_DecodeUTF16Stateful"], - make_string(s), - size, - make_string(errors), - byteorder, - consumed, - ) - - # PyUnicode_DecodeUTF32 - @staticmethod - def decode_utf_32( - s: StringLike, size: int, errors: StringLike, byteorder: PointerLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_DecodeUTF32"], - make_string(s), - size, - make_string(errors), - byteorder, - ) - - # PyUnicode_DecodeUTF32Stateful - @staticmethod - def decode_utf_32_stateful( - s: StringLike, - size: int, - errors: StringLike, - byteorder: PointerLike, - consumed: PointerLike, - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_DecodeUTF32Stateful"], - make_string(s), - size, - make_string(errors), - byteorder, - consumed, - ) - - # PyUnicode_DecodeUTF7 - @staticmethod - def decode_utf_7(s: StringLike, size: int, errors: StringLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_DecodeUTF7"], make_string(s), size, make_string(errors) - ) - - # PyUnicode_DecodeUTF7Stateful - @staticmethod - def decode_utf_7_stateful( - s: StringLike, size: int, errors: StringLike, consumed: PointerLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_DecodeUTF7Stateful"], - make_string(s), - size, - make_string(errors), - consumed, - ) - - # PyUnicode_DecodeUTF8 - @staticmethod - def decode_utf_8(s: StringLike, size: int, errors: StringLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_DecodeUTF8"], make_string(s), size, make_string(errors) - ) - - # PyUnicode_DecodeUTF8Stateful - @staticmethod - def decode_utf_8_stateful( - s: StringLike, size: int, errors: StringLike, consumed: PointerLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_DecodeUTF8Stateful"], - make_string(s), - size, - make_string(errors), - consumed, - ) - - # PyUnicode_DecodeUnicodeEscape - @staticmethod - def decode_unicode_escape( - s: StringLike, size: int, errors: StringLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_DecodeUnicodeEscape"], - make_string(s), - size, - make_string(errors), - ) - - # PyUnicode_EncodeFSDefault - @staticmethod - def encode_fs_default(unicode: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_EncodeFSDefault"], _deref_maybe(unicode) - ) - - # PyUnicode_EncodeLocale - @staticmethod - def encode_locale(unicode: PyObjectLike, errors: StringLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_EncodeLocale"], - _deref_maybe(unicode), - make_string(errors), - ) - - # PyUnicode_FSConverter - @staticmethod - def fs_converter(obj: PyObjectLike, result: PointerLike) -> int: - return api_binding_base( - API_FUNCS["PyUnicode_FSConverter"], _deref_maybe(obj), result - ) - - # PyUnicode_FSDecoder - @staticmethod - def fs_decoder(obj: PyObjectLike, result: PointerLike) -> int: - return api_binding_base( - API_FUNCS["PyUnicode_FSDecoder"], _deref_maybe(obj), result - ) - - # PyUnicode_Find - @staticmethod - def find( - str: PyObjectLike, substr: PyObjectLike, start: int, end: int, direction: int - ) -> int: - return api_binding_base( - API_FUNCS["PyUnicode_Find"], - _deref_maybe(str), - _deref_maybe(substr), - start, - end, - direction, - ) - - # PyUnicode_FindChar - @staticmethod - def find_char( - str: PyObjectLike, ch: int, start: int, end: int, direction: int - ) -> int: - return api_binding_base( - API_FUNCS["PyUnicode_FindChar"], - _deref_maybe(str), - ch, - start, - end, - direction, - ) - - # PyUnicode_Format - @staticmethod - def format(format: PyObjectLike, args: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_Format"], _deref_maybe(format), _deref_maybe(args) - ) - - # PyUnicode_FromEncodedObject - @staticmethod - def from_encoded_object( - obj: PyObjectLike, encoding: StringLike, errors: StringLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_FromEncodedObject"], - _deref_maybe(obj), - make_string(encoding), - make_string(errors), - ) - - # PyUnicode_FromFormatV - @staticmethod - def from_format_v(format: StringLike, vargs: PointerLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_FromFormatV"], make_string(format), vargs - ) - - # PyUnicode_FromObject - @staticmethod - def from_object(obj: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyUnicode_FromObject"], _deref_maybe(obj)) - - # PyUnicode_FromString - @staticmethod - def from_string(u: StringLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyUnicode_FromString"], make_string(u)) - - # PyUnicode_FromStringAndSize - @staticmethod - def from_string_and_size(u: StringLike, size: int) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_FromStringAndSize"], make_string(u), size - ) - - # PyUnicode_FromWideChar - @staticmethod - def from_wide_char(w: str, size: int) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyUnicode_FromWideChar"], w, size) - - # PyUnicode_GetLength - @staticmethod - def get_length(unicode: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyUnicode_GetLength"], _deref_maybe(unicode)) - - # PyUnicode_GetSize - @staticmethod - def get_size(unicode: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyUnicode_GetSize"], _deref_maybe(unicode)) - - # PyUnicode_InternFromString - @staticmethod - def intern_from_string(v: StringLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyUnicode_InternFromString"], make_string(v)) - - # PyUnicode_InternInPlace - @staticmethod - def intern_in_place(string: PointerLike) -> None: - return api_binding_base(API_FUNCS["PyUnicode_InternInPlace"], string) - - # PyUnicode_IsIdentifier - @staticmethod - def is_identifier(o: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["PyUnicode_IsIdentifier"], _deref_maybe(o)) - - # PyUnicode_Join - @staticmethod - def join(separator: PyObjectLike, seq: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_Join"], _deref_maybe(separator), _deref_maybe(seq) - ) - - # PyUnicode_ReadChar - @staticmethod - def read_char(unicode: PyObjectLike, index: int) -> int: - return api_binding_base( - API_FUNCS["PyUnicode_ReadChar"], _deref_maybe(unicode), index - ) - - # PyUnicode_Replace - @staticmethod - def replace( - str: PyObjectLike, substr: PyObjectLike, replstr: PyObjectLike, maxcount: int - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_Replace"], - _deref_maybe(str), - _deref_maybe(substr), - _deref_maybe(replstr), - maxcount, - ) - - # PyUnicode_RichCompare - @staticmethod - def rich_compare(left: PyObjectLike, right: PyObjectLike, op: int) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_RichCompare"], - _deref_maybe(left), - _deref_maybe(right), - op, - ) - - # PyUnicode_Split - @staticmethod - def split(s: PyObjectLike, sep: PyObjectLike, maxsplit: int) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_Split"], _deref_maybe(s), _deref_maybe(sep), maxsplit - ) - - # PyUnicode_Splitlines - @staticmethod - def splitlines(s: PyObjectLike, keepend: int) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_Splitlines"], _deref_maybe(s), keepend - ) - - # PyUnicode_Substring - @staticmethod - def substring(str: PyObjectLike, start: int, end: int) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_Substring"], _deref_maybe(str), start, end - ) - - # PyUnicode_Tailmatch - @staticmethod - def tailmatch( - str: PyObjectLike, substr: PyObjectLike, start: int, end: int, direction: int - ) -> int: - return api_binding_base( - API_FUNCS["PyUnicode_Tailmatch"], - _deref_maybe(str), - _deref_maybe(substr), - start, - end, - direction, - ) - - # PyUnicode_Translate - @staticmethod - def translate( - str: PyObjectLike, table: PyObjectLike, errors: StringLike - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyUnicode_Translate"], - _deref_maybe(str), - _deref_maybe(table), - make_string(errors), - ) - - # PyUnicode_WriteChar - @staticmethod - def write_char(unicode: PyObjectLike, index: int, character: int) -> int: - return api_binding_base( - API_FUNCS["PyUnicode_WriteChar"], _deref_maybe(unicode), index, character - ) - - -class PyWeakref(_CallBase): - """Namespace containing API functions prefixed with `PyWeakref_`""" - - # PyWeakref_GetObject - @staticmethod - def get_object(ref: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["PyWeakref_GetObject"], _deref_maybe(ref)) - - # PyWeakref_NewProxy - @staticmethod - def new_proxy(ob: PyObjectLike, callback: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyWeakref_NewProxy"], _deref_maybe(ob), _deref_maybe(callback) - ) - - # PyWeakref_NewRef - @staticmethod - def new_ref(ob: PyObjectLike, callback: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyWeakref_NewRef"], _deref_maybe(ob), _deref_maybe(callback) - ) - - -class Py(_CallBase): - """Namespace containing API functions prefixed with `Py_`""" - - # Py_AddPendingCall - @staticmethod - def add_pending_call(func: Callable[[PointerLike], int], arg: PointerLike) -> int: - return api_binding_base(API_FUNCS["Py_AddPendingCall"], func, arg) - - # Py_BytesMain - @staticmethod - def bytes_main(argc: int, argv: PointerLike) -> int: - return api_binding_base(API_FUNCS["Py_BytesMain"], argc, argv) - - # Py_CompileString - @staticmethod - def compile_string( - str: StringLike, filename: StringLike, start: int - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["Py_CompileString"], - make_string(str), - make_string(filename), - start, - ) - - # Py_DecRef - @staticmethod - def dec_ref(o: PyObjectLike) -> None: - return api_binding_base(API_FUNCS["Py_DecRef"], _deref_maybe(o)) - - # Py_DecodeLocale - @staticmethod - def decode_locale(arg: StringLike, size: PointerLike) -> str: - return api_binding_base(API_FUNCS["Py_DecodeLocale"], make_string(arg), size) - - # Py_EncodeLocale - @staticmethod - def encode_locale(text: str, error_pos: PointerLike) -> StringLike: - return api_binding_base(API_FUNCS["Py_EncodeLocale"], text, error_pos) - - # Py_EndInterpreter - @staticmethod - def end_interpreter(tstate: StructPointer[ThreadState]) -> None: - return api_binding_base(API_FUNCS["Py_EndInterpreter"], tstate) - - # Py_EnterRecursiveCall - @staticmethod - def enter_recursive_call(where: StringLike) -> int: - return api_binding_base(API_FUNCS["Py_EnterRecursiveCall"], make_string(where)) - - # Py_Exit - @staticmethod - def exit(status: int) -> None: - return api_binding_base(API_FUNCS["Py_Exit"], status) - - # Py_FatalError - @staticmethod - def fatal_error(message: StringLike) -> None: - return api_binding_base(API_FUNCS["Py_FatalError"], make_string(message)) - - # Py_Finalize - @staticmethod - def finalize() -> None: - return api_binding_base( - API_FUNCS["Py_Finalize"], - ) - - # Py_FinalizeEx - @staticmethod - def finalize_ex() -> int: - return api_binding_base( - API_FUNCS["Py_FinalizeEx"], - ) - - # Py_GenericAlias - @staticmethod - def generic_alias(origin: PyObjectLike, args: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["Py_GenericAlias"], _deref_maybe(origin), _deref_maybe(args) - ) - - # Py_GetBuildInfo - @staticmethod - def get_build_info() -> StringLike: - return api_binding_base( - API_FUNCS["Py_GetBuildInfo"], - ) - - # Py_GetCompiler - @staticmethod - def get_compiler() -> StringLike: - return api_binding_base( - API_FUNCS["Py_GetCompiler"], - ) - - # Py_GetCopyright - @staticmethod - def get_copyright() -> StringLike: - return api_binding_base( - API_FUNCS["Py_GetCopyright"], - ) - - # Py_GetExecPrefix - @staticmethod - def get_exec_prefix() -> str: - return api_binding_base( - API_FUNCS["Py_GetExecPrefix"], - ) - - # Py_GetPath - @staticmethod - def get_path() -> str: - return api_binding_base( - API_FUNCS["Py_GetPath"], - ) - - # Py_GetPlatform - @staticmethod - def get_platform() -> StringLike: - return api_binding_base( - API_FUNCS["Py_GetPlatform"], - ) - - # Py_GetPrefix - @staticmethod - def get_prefix() -> str: - return api_binding_base( - API_FUNCS["Py_GetPrefix"], - ) - - # Py_GetProgramFullPath - @staticmethod - def get_program_full_path() -> str: - return api_binding_base( - API_FUNCS["Py_GetProgramFullPath"], - ) - - # Py_GetProgramName - @staticmethod - def get_program_name() -> str: - return api_binding_base( - API_FUNCS["Py_GetProgramName"], - ) - - # Py_GetPythonHome - @staticmethod - def get_python_home() -> str: - return api_binding_base( - API_FUNCS["Py_GetPythonHome"], - ) - - # Py_GetVersion - @staticmethod - def get_version() -> StringLike: - return api_binding_base( - API_FUNCS["Py_GetVersion"], - ) - - # Py_IncRef - @staticmethod - def inc_ref(o: PyObjectLike) -> None: - return api_binding_base(API_FUNCS["Py_IncRef"], _deref_maybe(o)) - - # Py_Initialize - @staticmethod - def initialize() -> None: - return api_binding_base( - API_FUNCS["Py_Initialize"], - ) - - # Py_InitializeEx - @staticmethod - def initialize_ex(initsigs: int) -> None: - return api_binding_base(API_FUNCS["Py_InitializeEx"], initsigs) - - # Py_Is - @staticmethod - def is_(x: PyObjectLike, y: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["Py_Is"], _deref_maybe(x), _deref_maybe(y)) - - # Py_IsFalse - @staticmethod - def is_false(x: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["Py_IsFalse"], _deref_maybe(x)) - - # Py_IsInitialized - @staticmethod - def is_initialized() -> int: - return api_binding_base( - API_FUNCS["Py_IsInitialized"], - ) - - # Py_IsNone - @staticmethod - def is_none(x: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["Py_IsNone"], _deref_maybe(x)) - - # Py_IsTrue - @staticmethod - def is_true(x: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["Py_IsTrue"], _deref_maybe(x)) - - # Py_LeaveRecursiveCall - @staticmethod - def leave_recursive_call() -> None: - return api_binding_base( - API_FUNCS["Py_LeaveRecursiveCall"], - ) - - # Py_Main - @staticmethod - def main(argc: int, argv: PointerLike) -> int: - return api_binding_base(API_FUNCS["Py_Main"], argc, argv) - - # Py_NewInterpreter - @staticmethod - def new_interpreter() -> StructPointer[ThreadState]: - return api_binding_base( - API_FUNCS["Py_NewInterpreter"], - ) - - # Py_NewRef - @staticmethod - def new_ref(o: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["Py_NewRef"], _deref_maybe(o)) - - # Py_ReprEnter - @staticmethod - def repr_enter(object: PyObjectLike) -> int: - return api_binding_base(API_FUNCS["Py_ReprEnter"], _deref_maybe(object)) - - # Py_ReprLeave - @staticmethod - def repr_leave(object: PyObjectLike) -> None: - return api_binding_base(API_FUNCS["Py_ReprLeave"], _deref_maybe(object)) - - # Py_SetProgramName - @staticmethod - def set_program_name(name: str) -> None: - return api_binding_base(API_FUNCS["Py_SetProgramName"], name) - - # Py_SetPythonHome - @staticmethod - def set_python_home(home: str) -> None: - return api_binding_base(API_FUNCS["Py_SetPythonHome"], home) - - # Py_VaBuildValue - @staticmethod - def va_build_value(format: StringLike, vargs: PointerLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["Py_VaBuildValue"], make_string(format), vargs - ) - - # Py_XNewRef - @staticmethod - def x_new_ref(o: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["Py_XNewRef"], _deref_maybe(o)) - - -class PyContext(_CallBase): - """Namespace containing API functions prefixed with `PyContext_`""" - - # PyContext_New - @staticmethod - def new() -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyContext_New"], - ) - - # PyContext_CopyCurrent - @staticmethod - def copy_current() -> PyObjectLike: - return api_binding_base( - API_FUNCS["PyContext_CopyCurrent"], - ) - - -class _PyWarnings(_CallBase): - """Namespace containing API functions prefixed with `_PyWarnings_`""" - - # _PyWarnings_Init - @staticmethod - def init() -> PyObjectLike: - return api_binding_base( - API_FUNCS["_PyWarnings_Init"], - ) - - -class _PyFrame(_CallBase): - """Namespace containing API functions prefixed with `_PyFrame_`""" - - # _PyFrame_DebugMallocStats - @staticmethod - def debug_malloc_stats(out: PointerLike) -> None: - return api_binding_base(API_FUNCS["_PyFrame_DebugMallocStats"], out) - - -class _Py(_CallBase): - """Namespace containing API functions prefixed with `_Py_`""" - - # _Py_NewReference - @staticmethod - def new_reference(op: PyObjectLike) -> None: - return api_binding_base(API_FUNCS["_Py_NewReference"], _deref_maybe(op)) - - # _Py_CoerceLegacyLocale - @staticmethod - def coerce_legacy_locale(warn: int) -> int: - return api_binding_base(API_FUNCS["_Py_CoerceLegacyLocale"], warn) - - # _Py_LegacyLocaleDetected - @staticmethod - def legacy_locale_detected(warn: int) -> int: - return api_binding_base(API_FUNCS["_Py_LegacyLocaleDetected"], warn) - - # _Py_SetLocaleFromEnv - @staticmethod - def set_locale_from_env(category: int) -> StringLike: - return api_binding_base(API_FUNCS["_Py_SetLocaleFromEnv"], category) - - # _Py_NewInterpreter - @staticmethod - def new_interpreter(isolated_subinterpreter: int) -> StructPointer[ThreadState]: - return api_binding_base( - API_FUNCS["_Py_NewInterpreter"], isolated_subinterpreter - ) - - # _Py_DisplaySourceLine - @staticmethod - def display_source_line( - ob1: PyObjectLike, ob2: PyObjectLike, i1: int, i2: int - ) -> int: - return api_binding_base( - API_FUNCS["_Py_DisplaySourceLine"], - _deref_maybe(ob1), - _deref_maybe(ob2), - i1, - i2, - ) - - # _Py_DecodeLocaleEx - @staticmethod - def decode_locale_ex( - arg: StringLike, - wstr: PointerLike, - wlen: PointerLike, - reason: PointerLike, - current_locale: int, - ) -> int: - return api_binding_base( - API_FUNCS["_Py_DecodeLocaleEx"], - make_string(arg), - wstr, - wlen, - reason, - current_locale, - ) - - # _Py_EncodeLocaleEx - @staticmethod - def encode_locale_ex( - text: str, - str: PointerLike, - error_pos: PointerLike, - reason: PointerLike, - current_locale: int, - ) -> int: - return api_binding_base( - API_FUNCS["_Py_EncodeLocaleEx"], - text, - str, - error_pos, - reason, - current_locale, - ) - - # _Py_EncodeLocaleRaw - @staticmethod - def encode_locale_raw(text: str, error_pos: PointerLike) -> StringLike: - return api_binding_base(API_FUNCS["_Py_EncodeLocaleRaw"], text, error_pos) - - # _Py_DumpExtensionModules - @staticmethod - def dump_extension_modules( - fd: int, interp: StructPointer[InterpreterState] - ) -> None: - return api_binding_base(API_FUNCS["_Py_DumpExtensionModules"], fd, interp) - - # _Py_UTF8_Edit_Cost - @staticmethod - def utf_8_edit_cost( - str_a: PyObjectLike, str_b: PyObjectLike, max_cost: int - ) -> int: - return api_binding_base( - API_FUNCS["_Py_UTF8_Edit_Cost"], - _deref_maybe(str_a), - _deref_maybe(str_b), - max_cost, - ) - - -class PyCompile(_CallBase): - """Namespace containing API functions prefixed with `PyCompile_`""" - - # PyCompile_OpcodeStackEffect - @staticmethod - def opcode_stack_effect(opcode: int, oparg: int) -> int: - return api_binding_base(API_FUNCS["PyCompile_OpcodeStackEffect"], opcode, oparg) - - # PyCompile_OpcodeStackEffectWithJump - @staticmethod - def opcode_stack_effect_with_jump(opcode: int, oparg: int, jump: int) -> int: - return api_binding_base( - API_FUNCS["PyCompile_OpcodeStackEffectWithJump"], opcode, oparg, jump - ) - - -class _PyTraceback(_CallBase): - """Namespace containing API functions prefixed with `_PyTraceback_`""" - - # _PyTraceback_Add - @staticmethod - def add(a: StringLike, b: StringLike, i: int) -> None: - return api_binding_base( - API_FUNCS["_PyTraceback_Add"], make_string(a), make_string(b), i - ) - - -class _PyImport(_CallBase): - """Namespace containing API functions prefixed with `_PyImport_`""" - - # _PyImport_GetModuleId - @staticmethod - def get_module_id() -> PyObjectLike: - return api_binding_base( - API_FUNCS["_PyImport_GetModuleId"], - ) - - # _PyImport_SetModule - @staticmethod - def set_module(name: PyObjectLike, module: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["_PyImport_SetModule"], _deref_maybe(name), _deref_maybe(module) - ) - - # _PyImport_SetModuleString - @staticmethod - def set_module_string(name: StringLike, module: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["_PyImport_SetModuleString"], - make_string(name), - _deref_maybe(module), - ) - - # _PyImport_AcquireLock - @staticmethod - def acquire_lock() -> None: - return api_binding_base( - API_FUNCS["_PyImport_AcquireLock"], - ) - - # _PyImport_ReleaseLock - @staticmethod - def release_lock() -> int: - return api_binding_base( - API_FUNCS["_PyImport_ReleaseLock"], - ) - - -class _PyErr(_CallBase): - """Namespace containing API functions prefixed with `_PyErr_`""" - - # _PyErr_WriteUnraisableMsg - @staticmethod - def write_unraisable_msg(err_msg: StringLike, obj: PyObjectLike) -> None: - return api_binding_base( - API_FUNCS["_PyErr_WriteUnraisableMsg"], - make_string(err_msg), - _deref_maybe(obj), - ) - - # _PyErr_Fetch - @staticmethod - def fetch( - tstate: StructPointer[ThreadState], - type: PointerLike, - value: PointerLike, - traceback: PointerLike, - ) -> None: - return api_binding_base( - API_FUNCS["_PyErr_Fetch"], tstate, type, value, traceback - ) - - # _PyErr_ExceptionMatches - @staticmethod - def exception_matches(tstate: StructPointer[ThreadState], exc: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["_PyErr_ExceptionMatches"], tstate, _deref_maybe(exc) - ) - - # _PyErr_Restore - @staticmethod - def restore( - tstate: StructPointer[ThreadState], - type: PyObjectLike, - value: PyObjectLike, - traceback: PyObjectLike, - ) -> None: - return api_binding_base( - API_FUNCS["_PyErr_Restore"], - tstate, - _deref_maybe(type), - _deref_maybe(value), - _deref_maybe(traceback), - ) - - # _PyErr_SetObject - @staticmethod - def set_object( - tstate: StructPointer[ThreadState], type: PyObjectLike, value: PyObjectLike - ) -> None: - return api_binding_base( - API_FUNCS["_PyErr_SetObject"], - tstate, - _deref_maybe(type), - _deref_maybe(value), - ) - - # _PyErr_ChainStackItem - @staticmethod - def chain_stack_item() -> None: - return api_binding_base( - API_FUNCS["_PyErr_ChainStackItem"], - ) - - # _PyErr_Clear - @staticmethod - def clear(tstate: StructPointer[ThreadState]) -> None: - return api_binding_base(API_FUNCS["_PyErr_Clear"], tstate) - - # _PyErr_SetNone - @staticmethod - def set_none(tstate: StructPointer[ThreadState], exception: PyObjectLike) -> None: - return api_binding_base( - API_FUNCS["_PyErr_SetNone"], tstate, _deref_maybe(exception) - ) - - # _PyErr_NoMemory - @staticmethod - def no_memory(tstate: StructPointer[ThreadState]) -> PyObjectLike: - return api_binding_base(API_FUNCS["_PyErr_NoMemory"], tstate) - - # _PyErr_SetString - @staticmethod - def set_string( - tstate: StructPointer[ThreadState], exception: PyObjectLike, string: StringLike - ) -> None: - return api_binding_base( - API_FUNCS["_PyErr_SetString"], - tstate, - _deref_maybe(exception), - make_string(string), - ) - - # _PyErr_NormalizeException - @staticmethod - def normalize_exception( - tstate: StructPointer[ThreadState], - exc: PointerLike, - val: PointerLike, - tb: PointerLike, - ) -> None: - return api_binding_base( - API_FUNCS["_PyErr_NormalizeException"], tstate, exc, val, tb - ) - - # _PyErr_CheckSignalsTstate - @staticmethod - def check_signals_tstate(tstate: StructPointer[ThreadState]) -> int: - return api_binding_base(API_FUNCS["_PyErr_CheckSignalsTstate"], tstate) - - -class _PyInterpreterState(_CallBase): - """Namespace containing API functions prefixed with `_PyInterpreterState_`""" - - # _PyInterpreterState_RequireIDRef - @staticmethod - def require_id_ref(interp: StructPointer[InterpreterState], i: int) -> None: - return api_binding_base( - API_FUNCS["_PyInterpreterState_RequireIDRef"], interp, i - ) - - -class _PyBytesWriter(_CallBase): - """Namespace containing API functions prefixed with `_PyBytesWriter_`""" - - # _PyBytesWriter_WriteBytes - @staticmethod - def write_bytes(writer: PointerLike, str: PointerLike, bytes: int) -> PointerLike: - return api_binding_base( - API_FUNCS["_PyBytesWriter_WriteBytes"], writer, str, bytes - ) - - -class _PyEval(_CallBase): - """Namespace containing API functions prefixed with `_PyEval_`""" - - # _PyEval_SetTrace - @staticmethod - def set_trace(tstate: StructPointer[ThreadState], func: PyObjectLike) -> int: - return api_binding_base( - API_FUNCS["_PyEval_SetTrace"], tstate, _deref_maybe(func) - ) - - # _PyEval_GetCoroutineOriginTrackingDepth - @staticmethod - def get_coroutine_origin_tracking_depth() -> int: - return api_binding_base( - API_FUNCS["_PyEval_GetCoroutineOriginTrackingDepth"], - ) - - # _PyEval_GetAsyncGenFirstiter - @staticmethod - def get_async_gen_firstiter() -> PyObjectLike: - return api_binding_base( - API_FUNCS["_PyEval_GetAsyncGenFirstiter"], - ) - - # _PyEval_GetAsyncGenFinalizer - @staticmethod - def get_async_gen_finalizer() -> PyObjectLike: - return api_binding_base( - API_FUNCS["_PyEval_GetAsyncGenFinalizer"], - ) - - # _PyEval_EvalFrameDefault - @staticmethod - def eval_frame_default( - tstate: StructPointer[ThreadState], f: StructPointer[FrameObject], exc: int - ) -> PyObjectLike: - return api_binding_base(API_FUNCS["_PyEval_EvalFrameDefault"], tstate, f, exc) - - # _PyEval_SetSwitchInterval - @staticmethod - def set_switch_interval(microseconds: int) -> None: - return api_binding_base(API_FUNCS["_PyEval_SetSwitchInterval"], microseconds) - - # _PyEval_GetSwitchInterval - @staticmethod - def get_switch_interval() -> int: - return api_binding_base( - API_FUNCS["_PyEval_GetSwitchInterval"], - ) - - -class _PyDictView(_CallBase): - """Namespace containing API functions prefixed with `_PyDictView_`""" - - # _PyDictView_Intersect - @staticmethod - def intersect(slf: PyObjectLike, other: PyObjectLike) -> PyObjectLike: - return api_binding_base( - API_FUNCS["_PyDictView_Intersect"], _deref_maybe(slf), _deref_maybe(other) - ) - - -class _PyRun(_CallBase): - """Namespace containing API functions prefixed with `_PyRun_`""" - - # _PyRun_SimpleFileObject - @staticmethod - def simple_file_object( - fp: PointerLike, filename: PyObjectLike, closeit: int - ) -> int: - return api_binding_base( - API_FUNCS["_PyRun_SimpleFileObject"], fp, _deref_maybe(filename), closeit - ) - - -class _PySys(_CallBase): - """Namespace containing API functions prefixed with `_PySys_`""" - - # _PySys_GetObjectId - @staticmethod - def get_object_id() -> PyObjectLike: - return api_binding_base( - API_FUNCS["_PySys_GetObjectId"], - ) - - -class _PyTuple(_CallBase): - """Namespace containing API functions prefixed with `_PyTuple_`""" - - # _PyTuple_DebugMallocStats - @staticmethod - def debug_malloc_stats(out: PointerLike) -> None: - return api_binding_base(API_FUNCS["_PyTuple_DebugMallocStats"], out) - - -class _PyNumber(_CallBase): - """Namespace containing API functions prefixed with `_PyNumber_`""" - - # _PyNumber_Index - @staticmethod - def index(o: PyObjectLike) -> PyObjectLike: - return api_binding_base(API_FUNCS["_PyNumber_Index"], _deref_maybe(o)) - - -class _PyAST(_CallBase): - """Namespace containing API functions prefixed with `_PyAST_`""" - - # _PyAST_Compile - @staticmethod - def compile(mod: PyObjectLike, filename: int) -> StructPointer[CodeObject]: - return api_binding_base( - API_FUNCS["_PyAST_Compile"], _deref_maybe(mod), filename - ) - - -class _PyStructSequence(_CallBase): - """Namespace containing API functions prefixed with `_PyStructSequence_`""" - - # _PyStructSequence_InitType - @staticmethod - def init_type(type: StructPointer[TypeObject], desc: int) -> int: - return api_binding_base(API_FUNCS["_PyStructSequence_InitType"], type, desc) - - -class _PyObject(_CallBase): - """Namespace containing API functions prefixed with `_PyObject_`""" - - # _PyObject_Call_Prepend - @staticmethod - def call_prepend( - tstate: StructPointer[ThreadState], - callable: PyObjectLike, - obj: PyObjectLike, - args: PyObjectLike, - kwargs: PyObjectLike, - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["_PyObject_Call_Prepend"], - tstate, - _deref_maybe(callable), - _deref_maybe(obj), - _deref_maybe(args), - _deref_maybe(kwargs), - ) - - # _PyObject_FastCallDictTstate - @staticmethod - def fast_call_dict_tstate( - tstate: StructPointer[ThreadState], - callable: PyObjectLike, - args: PointerLike, - nargsf: int, - kwargs: PyObjectLike, - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["_PyObject_FastCallDictTstate"], - tstate, - _deref_maybe(callable), - args, - nargsf, - _deref_maybe(kwargs), - ) - - # _PyObject_Call - @staticmethod - def call( - tstate: StructPointer[ThreadState], - callable: PyObjectLike, - args: PyObjectLike, - kwargs: PyObjectLike, - ) -> PyObjectLike: - return api_binding_base( - API_FUNCS["_PyObject_Call"], - tstate, - _deref_maybe(callable), - _deref_maybe(args), - _deref_maybe(kwargs), - ) - - -class _PyType(_CallBase): - """Namespace containing API functions prefixed with `_PyType_`""" - - # _PyType_CheckConsistency - @staticmethod - def check_consistency(type: StructPointer[TypeObject]) -> int: - return api_binding_base(API_FUNCS["_PyType_CheckConsistency"], type) - - -class _PyDict(_CallBase): - """Namespace containing API functions prefixed with `_PyDict_`""" - - # _PyDict_CheckConsistency - @staticmethod - def check_consistency(mp: PyObjectLike, check_content: int) -> int: - return api_binding_base( - API_FUNCS["_PyDict_CheckConsistency"], _deref_maybe(mp), check_content - ) diff --git a/src/pointers/base_pointers.py b/src/pointers/base_pointers.py deleted file mode 100644 index 15b208e..0000000 --- a/src/pointers/base_pointers.py +++ /dev/null @@ -1,461 +0,0 @@ -import ctypes -import gc -import sys -import weakref -from abc import ABC, abstractmethod -from contextlib import suppress -from typing import (Any, Generic, Iterator, Optional, Tuple, Type, TypeVar, - Union) - -from _pointers import add_ref, remove_ref -from typing_extensions import final - -from ._utils import deref, force_set_attr, move_to_mem -from .exceptions import DereferenceError, FreedMemoryError, NullPointerError -from .util import NULL, Nullable, handle - -__all__ = ( - "BasePointer", - "BaseObjectPointer", - "BasicPointer", - "BaseCPointer", - "BaseAllocatedPointer", - "Dereferencable", - "IterDereferencable", -) - -T = TypeVar("T") -A = TypeVar("A", bound="BasicPointer") - - -class BasicPointer(ABC): - """Base class representing a pointer with no operations.""" - - @property - @abstractmethod - def address(self) -> Optional[int]: - """Address that the pointer is looking at.""" - ... - - @abstractmethod - def __repr__(self) -> str: - ... - - @final - def __str__(self) -> str: - return f"{type(self).__name__}({hex(self.address or 0)})" - - @abstractmethod - def _cleanup(self) -> None: - ... - - @final - def __eq__(self, data: object) -> bool: - if not isinstance(data, BasePointer): - return False - - return data.address == self.address - - @final - def ensure(self) -> int: - """Ensure that the pointer is not null. - - Raises: - NullPointerError: Address of pointer is `None` - - Returns: - Address of the pointer. - - Example: - ```py - ptr = to_ptr(NULL) - address = ptr.ensure() # NullPointerError - ptr >>= 1 - address = ptr.ensure() # works just fine - ```""" - - if not self.address: - raise NullPointerError("pointer is NULL") - return self.address - - -class Movable(ABC, Generic[T, A]): - @abstractmethod - def move( - self, - data: Union[A, T], - *, - unsafe: bool = False, - ) -> None: - """Move/copy a value into the memory at the pointers address.""" - ... - - def __ilshift__(self, data: Union[A, T]): - self.move(data) - return self - - def __ixor__(self, data: Union[A, T]): - self.move(data, unsafe=True) - return self - - -class Dereferencable(ABC, Generic[T]): - """Abstract class for an object that may be dereferenced.""" - - @abstractmethod - def dereference(self) -> T: - """Dereference the pointer. - - Returns: - Value at the pointers address.""" - ... - - @final - def __invert__(self) -> T: - return self.dereference() - - -class IterDereferencable(Dereferencable[T], Generic[T]): - """ - Abstract class for an object that may be dereferenced via * (`__iter__`) - """ - - def __iter__(self) -> Iterator[T]: - return iter({self.dereference()}) - - -class BasePointer( - Dereferencable[T], - Movable[T, "BasePointer[T]"], - BasicPointer, - ABC, - Generic[T], -): - """Base class representing a pointer.""" - - @abstractmethod - def __repr__(self) -> str: - ... - - @abstractmethod - def _cleanup(self) -> None: - ... - - -class Sized(BasicPointer, ABC): - """Base class for a pointer that has a size attribute.""" - - @property - @abstractmethod - def size(self) -> int: - """Size of the target value.""" - ... - - @handle - @final - def make_ct_pointer(self) -> "ctypes._PointerLike": - """Convert the address to a ctypes pointer. - - Returns: - The created ctypes pointer. - """ - return ctypes.cast( - self.ensure(), - ctypes.POINTER(ctypes.c_char * self.size), - ) - - @abstractmethod - def _make_stream_and_ptr( - self, - size: int, - address: int, - ) -> Tuple["ctypes._PointerLike", bytes]: - ... - - -class BaseObjectPointer( - IterDereferencable[T], - BasePointer[T], - ABC, -): - """Abstract class for a pointer to a Python object.""" - - def __init__( - self, - address: Optional[int], - increment_ref: bool = False, - ) -> None: - """ - Args: - address: Address of the underlying value. - increment_ref: Should the reference count on the target object get incremented. - """ # noqa - self._address: Optional[int] = address - - if increment_ref and address: - add_ref(~self) - - self._origin_size = sys.getsizeof(~self if address else None) - weakref.finalize(self, self._cleanup) - - @handle - def set_attr(self, key: str, value: Any) -> None: - """Force setting an attribute on the object the pointer is looking at.""" # noqa - v: Any = ~self # mypy gets angry if this isnt any - if not isinstance(~self, type): - v = type(v) - - force_set_attr(v, key, value) - - @handle - def assign( - self, - target: Nullable[Union["BaseObjectPointer[T]", T]], - ) -> None: - """Point to a new address. - - Args: - target: New pointer or value to look at. - """ - if target is NULL: - self._address = None - return - - new: BasePointer[T] = self._get_ptr(target) # type: ignore - - if not isinstance(new, BaseObjectPointer): - raise ValueError( - "can only point to object pointer", - ) - - with suppress(NullPointerError): - remove_ref(~self) - - self._address = new.address - add_ref(~self) - - @property - def address(self) -> Optional[int]: - return self._address - - @handle - def dereference(self) -> T: - return deref(self.ensure()) - - def __irshift__( - self, - value: Nullable[Union["BaseObjectPointer[T]", T]], - ): - self.assign(value) - return self - - @classmethod - @abstractmethod - def make_from(cls, obj: T) -> "BaseObjectPointer[T]": - """Create a new instance of the pointer. - - Args: - obj: Object to create pointer to. - - Returns: - Created pointer. - - Example: - ```py - ptr = Pointer.make_from(1) - ```""" - ... - - @classmethod - def _get_ptr(cls, obj: Union[T, "BasePointer[T]"]) -> "BasePointer[T]": - return ( - obj - if isinstance( - obj, - BasePointer, - ) - else cls.make_from(obj) - ) - - def _cleanup(self) -> None: - if self.address: - remove_ref(~self) - - -class BaseCPointer( - Movable[T, "BaseCPointer[T]"], - IterDereferencable[T], - Sized, - ABC, -): - def __init__(self, address: int, size: int): - self._address = address - self._size = size - weakref.finalize(self, self._cleanup) - - @property - def address(self) -> Optional[int]: - return self._address - - def _make_stream_and_ptr( - self, - size: int, - address: int, - ) -> Tuple["ctypes._PointerLike", bytes]: - bytes_a = (ctypes.c_ubyte * size).from_address(address) - return self.make_ct_pointer(), bytes(bytes_a) - - @handle - def move( - self, - data: Union["BaseCPointer[T]", T], - *, - unsafe: bool = False, - ) -> None: - """Move data to the target address.""" - if not isinstance(data, BaseCPointer): - raise ValueError( - f'"{type(data).__name__}" object is not a valid C pointer', - ) - - ptr, byte_stream = self._make_stream_and_ptr( - data.size, - data.ensure(), - ) - move_to_mem(ptr, byte_stream, unsafe=unsafe, target="C data") - - def __ilshift__(self, data: Union["BaseCPointer[T]", T]): - self.move(data) - return self - - def __ixor__(self, data: Union["BaseCPointer[T]", T]): - self.move(data, unsafe=True) - return self - - @handle - def make_ct_pointer(self): - """Turn the pointer into a ctypes pointer.""" - return ctypes.cast( - self.ensure(), - ctypes.POINTER(ctypes.c_char * self.size), - ) - - @abstractmethod - def _as_parameter_(self) -> "ctypes._CData": - """Convert the data into something that ctypes understands.""" - ... - - @abstractmethod - def _cleanup(self) -> None: - ... - - -class BaseAllocatedPointer(BasePointer[T], Sized, ABC): - @property - @abstractmethod - def address(self) -> Optional[int]: - ... - - @address.setter - def address(self, value: int) -> None: - ... - - @property - @abstractmethod - def freed(self) -> bool: - ... - - @freed.setter - def freed(self, value: bool) -> None: - self._freed = value - - @property - def assigned(self) -> bool: - """Whether the allocated memory has been assigned a value.""" - return self._assigned - - @assigned.setter - def assigned(self, value: bool) -> None: - self._assigned = value - - @handle - def move( - self, - data: Union[BasePointer[T], T], - unsafe: bool = False, - ) -> None: - add_ref(data) - self.ensure_valid() - from .object_pointer import to_ptr - - data_ptr = data if isinstance(data, BasePointer) else to_ptr(data) - - if (sys.version_info.minor >= 11) and (gc.is_tracked(~data_ptr)): - remove_ref(data) - raise RuntimeError("allocation on tracked types is not supported on 3.11+") - - - ptr, byte_stream = self._make_stream_and_ptr( - sys.getsizeof(~data_ptr), - data_ptr.ensure(), - ) - - move_to_mem(ptr, byte_stream, unsafe=unsafe) - self.assigned = True - remove_ref(data) - - @handle - def dereference(self) -> T: - if self.freed: - raise FreedMemoryError( - "cannot dereference memory that has been freed", - ) - - if not self.assigned: - raise DereferenceError( - "cannot dereference allocated memory that has no value", - ) - - return deref(self.ensure()) - - @abstractmethod - def __add__(self, amount: int) -> "BaseAllocatedPointer[Any]": - ... - - @abstractmethod - def __sub__(self, amount: int) -> "BaseAllocatedPointer[Any]": - ... - - def _cleanup(self) -> None: - pass - - def _make_stream_and_ptr( - self, - size: int, - address: int, - ) -> Tuple["ctypes._PointerLike", bytes]: - if self.freed: - raise FreedMemoryError("memory has been freed") - - bytes_a = (ctypes.c_ubyte * size).from_address(address) # fmt: off - return self.make_ct_pointer(), bytes(bytes_a) - - @abstractmethod - def free(self) -> None: - """Free the memory.""" - ... - - def ensure_valid(self) -> None: - """Ensure the memory has not been freed.""" - if self.freed: - raise FreedMemoryError( - f"{self} has been freed", - ) - - @property - def size(self) -> int: - return self._size - - @size.setter - def size(self, value: int) -> None: - self._size = value diff --git a/src/pointers/bindings.py b/src/pointers/bindings.py deleted file mode 100644 index 2d2b862..0000000 --- a/src/pointers/bindings.py +++ /dev/null @@ -1,1103 +0,0 @@ -import ctypes -import inspect -import warnings -from types import FunctionType -from typing import ( - TYPE_CHECKING, - Any, - Callable, - Dict, - Iterable, - Iterator, - Optional, - Sequence, - Type, - TypeVar, - Union, -) - -from _pointers import add_ref - -from ._cstd import c_calloc as _calloc -from ._cstd import c_free as _free -from ._cstd import c_malloc as _malloc -from ._cstd import c_raise as ct_raise -from ._cstd import c_realloc as _realloc -from ._cstd import dll, mdll -from ._utils import get_mapped, get_py -from .base_pointers import BaseCPointer, BasePointer -from .c_pointer import TypedCPointer, VoidPointer -from .exceptions import InvalidBindingParameter -from .std_structs import STRUCT_MAP, DivT, Lconv, LDivT, Tm -from .structure import StructPointer -from .util import NULL, Nullable, handle - -if TYPE_CHECKING: - from .structure import Struct - -T = TypeVar("T") - -PointerLike = Nullable[Optional[Union[TypedCPointer[T], VoidPointer]]] -StringLike = Optional[Union[str, bytes, VoidPointer, TypedCPointer[bytes]]] -Format = Union[StringLike, PointerLike] -TypedPtr = Optional[PointerLike[T]] -PyCFuncPtrType = type(ctypes.CFUNCTYPE(None)) - -__all__ = ( - "isalnum", - "isalpha", - "iscntrl", - "isdigit", - "isgraph", - "islower", - "isprint", - "ispunct", - "isspace", - "isupper", - "isxdigit", - "tolower", - "toupper", - "setlocale", - "frexp", - "ldexp", - "modf", - "fclose", - "clearerr", - "feof", - "ferror", - "fflush", - "fgetpos", - "fopen", - "fread", - "freopen", - "fseek", - "fsetpos", - "ftell", - "fwrite", - "remove", - "rename", - "rewind", - "setbuf", - "setvbuf", - "tmpfile", - "tmpnam", - "fprintf", - "printf", - "sprintf", - "fscanf", - "scanf", - "sscanf", - "fgetc", - "fgets", - "fputc", - "fputs", - "getc", - "getchar", - "gets", - "putc", - "putchar", - "puts", - "ungetc", - "perror", - "strtod", - "strtol", - "strtoul", - "abort", - "exit", - "getenv", - "system", - "abs", - "labs", - "rand", - "srand", - "mblen", - "mbstowcs", - "mbtowc", - "wcstombs", - "wctomb", - "memchr", - "memcmp", - "memcpy", - "memmove", - "memset", - "strcat", - "strncat", - "strchr", - "strcmp", - "strncmp", - "strcoll", - "strcpy", - "strncpy", - "strcspn", - "strerror", - "strlen", - "strpbrk", - "strrchr", - "strspn", - "strstr", - "strtok", - "strxfrm", - "asctime", - "clock", - "ctime", - "difftime", - "mktime", - "strftime", - "time", - "div", - "ldiv", - "localeconv", - "c_raise", - "c_malloc", - "c_calloc", - "c_realloc", - "c_free", - "gmtime", - "signal", - "qsort", - "bsearch", - "sizeof", - "PointerLike", - "StringLike", - "Format", - "TypedPtr", -) - - -def _not_null(data: Optional[T]) -> T: - assert data is not None, f"{data} is None" - return data - - -StructMap = Dict[Type[ctypes.Structure], Type["Struct"]] -CharLike = Union[StringLike, int] - - -class _CFuncTransport: - def __init__( - self, - c_func: "ctypes._FuncPointer", - py_func: Callable, - ) -> None: - add_ref(c_func) - self._c_func = c_func - self._py_func = py_func - - @property - def c_func(self) -> "ctypes._FuncPointer": - return self._c_func - - @property - def py_func(self) -> Callable: - return self._py_func - - -def _decode_type( - res: Any, - struct_map: StructMap, - current: Optional[Type["ctypes._CData"]], -) -> Any: - res_typ = type(res) - - if res_typ.__name__.startswith("LP_"): - struct_type = struct_map.get(res_typ._type_) # type: ignore - - struct = ( - struct_type.from_existing(res.contents) if struct_type else None - ) # fmt: off - - res = ( - TypedCPointer( - ctypes.addressof(res), - res_typ, - ctypes.sizeof(res), - alt=True, - ) - if not issubclass(type(res.contents), ctypes.Structure) - else StructPointer(id(struct), struct) - ) - # type safety gets mad if i dont use elif here - elif current is ctypes.c_void_p: - res = VoidPointer(res, ctypes.sizeof(ctypes.c_void_p(res))) - - elif issubclass(res_typ, ctypes.Structure): - st = struct_map.get(res_typ) - if st: - res = st.from_existing(res) - - elif isinstance(res, bytes): - return res.decode() - - return res - - -def _decode_response( - res: Any, - struct_map: StructMap, - fn: "ctypes._NamedFuncPointer", -) -> Any: - return _decode_type(res, struct_map, fn.restype) # type: ignore - - -def _process_args( - args: Iterable[Any], - argtypes: Sequence[Type["ctypes._CData"]], - name: str, - struct_map: StructMap, -) -> None: - for index, (value, typ) in enumerate(zip(args, argtypes)): - if value is inspect._empty: - continue - - if isinstance(value, _CFuncTransport): - py_func = value.py_func - sig = inspect.signature(py_func) - _process_args( - [param.annotation for param in sig.parameters.values()], - value.c_func._argtypes_, # type: ignore - py_func.__name__, - struct_map, - ) - continue - is_c_func: bool = isinstance( - typ, - PyCFuncPtrType, - ) - n_type = get_py(typ) if not is_c_func else FunctionType - - if typ.__name__.startswith("LP_"): - ptr_tp = typ._type_ # type: ignore - if issubclass(ptr_tp, ctypes.Structure): # type: ignore - n_type = StructPointer - struct = struct_map.get(ptr_tp) - - if not struct: - warnings.warn( - f"struct {ptr_tp.__name__} not in struct map", - UserWarning, - ) - - is_type: bool = isinstance(value, type) - - if n_type is Any: - continue - - if not (isinstance if not is_type else issubclass)(value, n_type): - v_type = type(value) if not is_type else value - - if (n_type in {BasePointer, BaseCPointer, StructPointer}) and ( - value is None - ): - continue - - if (n_type is FunctionType) and is_c_func: - continue - - if ( - typ - in { - ctypes.c_char_p, - ctypes.c_void_p, - } - ) and (value is None): - continue - - if ((v_type is ctypes.c_char_p) and (n_type is bytes)) or ( - issubclass(v_type, BaseCPointer) and (typ is ctypes.c_void_p) - ): - continue - - raise InvalidBindingParameter( - f"argument {index + 1} of {name} got invalid type: expected {n_type.__name__}, got {v_type.__name__}" # noqa - ) - - -def _validate_args( - args: Iterable[Any], - fn: "ctypes._NamedFuncPointer", - struct_map: StructMap, -) -> None: - if not fn.argtypes: - return - - _process_args(args, fn.argtypes, fn.__name__, struct_map) - - -def _solve_func( - fn: Callable, - ct_fn: "ctypes._FuncPointer", - struct_map: StructMap, -) -> _CFuncTransport: - at = ct_fn._argtypes_ # type: ignore - - @ctypes.CFUNCTYPE(ct_fn._restype_, *at) # type: ignore - def wrapper(*args): - callback_args = [] - - for value, ctype in zip(args, at): - callback_args.append(_decode_type(value, struct_map, ctype)) - - return fn(*callback_args) - - return _CFuncTransport(wrapper, fn) - - -@handle -def binding_base( - fn: "ctypes._NamedFuncPointer", - *simple_args, - map_extra: Optional[StructMap] = None, -) -> Any: - smap = {**STRUCT_MAP, **(map_extra or {})} - - args = [i if i is not NULL else None for i in simple_args] - - validator_args = [ - arg - if ( - (not isinstance(arg, FunctionType)) - and (not isinstance(arg, PyCFuncPtrType)) - ) - else _solve_func( - arg, # type: ignore - typ, # type: ignore - smap, - ) - for arg, typ in zip( - args, - fn.argtypes or [None for _ in args], # type: ignore - ) - ] - - _validate_args( - validator_args, - fn, - smap, - ) - - res = fn( - *[ - i - if not isinstance( - i, - _CFuncTransport, - ) - else i.c_func - for i in validator_args - ] - ) - - return _decode_response( - res, - smap, - fn, - ) - -@handle -def make_string(data: StringLike) -> Union[bytes, ctypes.c_char_p]: - if (type(data) not in {VoidPointer, str, bytes, TypedCPointer}) and data: - raise InvalidBindingParameter( - f"expected a string-like object, got {repr(data)}" # noqa - ) - - if isinstance(data, bytes): - return data - - is_typed_ptr: bool = isinstance(data, TypedCPointer) - - if isinstance(data, VoidPointer) or isinstance(data, TypedCPointer): - # mypy is forcing me to call this twice - if is_typed_ptr and (data.type is not bytes): # type: ignore - raise InvalidBindingParameter( - f"{data} does not point to bytes", - ) - - if is_typed_ptr and (not data.alt): # type: ignore - return ctypes.c_char_p.from_address(data.ensure()) - return ctypes.c_char_p(data.ensure()) - - if isinstance(data, str): - return data.encode() - - if not data: - data = ctypes.c_char_p(None) # type: ignore - - assert isinstance(data, ctypes.c_char_p), f"{data} is not a char*" - return data - - -def make_format(*args: Format) -> Iterator[Format]: - for i in args: - if isinstance(i, (VoidPointer, str, bytes)): - yield make_string(i) # type: ignore - continue - - yield i - - -def make_char(char: CharLike) -> bytes: - if isinstance(char, int): - return chr(char).encode() - - charp = make_string(char) - string = ( - charp - if not isinstance( - charp, - ctypes.c_char_p, - ) - else _not_null(charp.value) - ) - - if len(string) != 1: - raise InvalidBindingParameter( - f'"{string.decode()}" should have a length of 1', - ) - - return string - - -def isalnum(c: CharLike) -> int: - return binding_base(dll.isalnum, make_char(c)) - - -def isalpha(c: CharLike) -> int: - return binding_base(dll.isalpha, make_char(c)) - - -def iscntrl(c: CharLike) -> int: - return binding_base(dll.iscntrl, make_char(c)) - - -def isdigit(c: CharLike) -> int: - return binding_base(dll.isdigit, make_char(c)) - - -def isgraph(c: CharLike) -> int: - return binding_base(dll.isgraph, make_char(c)) - - -def islower(c: CharLike) -> int: - return binding_base(dll.islower, make_char(c)) - - -def isprint(c: CharLike) -> int: - return binding_base(dll.isprint, make_char(c)) - - -def ispunct(c: CharLike) -> int: - return binding_base(dll.ispunct, make_char(c)) - - -def isspace(c: CharLike) -> int: - return binding_base(dll.isspace, make_char(c)) - - -def isupper(c: CharLike) -> int: - return binding_base(dll.isupper, make_char(c)) - - -def isxdigit(c: CharLike) -> int: - return binding_base(dll.isxdigit, make_char(c)) - - -def tolower(c: CharLike) -> str: - return binding_base(dll.tolower, make_char(c)) - - -def toupper(c: CharLike) -> str: - return binding_base(dll.toupper, make_char(c)) - - -def setlocale(category: int, locale: StringLike) -> str: - return binding_base(dll.setlocale, category, make_string(locale)) - - -def frexp(x: float, exponent: TypedPtr[int]) -> int: - return binding_base(mdll.frexp, x, exponent) - - -def ldexp(x: float, exponent: int) -> int: - return binding_base(mdll.ldexp, x, exponent) - - -def modf(x: float, integer: TypedPtr[float]) -> int: - return binding_base(mdll.modf, x, integer) - - -def fclose(stream: PointerLike) -> int: - return binding_base(dll.fclose, stream) - - -def clearerr(stream: PointerLike) -> None: - return binding_base(dll.clearerr, stream) - - -def feof(stream: PointerLike) -> int: - return binding_base(dll.feof, stream) - - -def ferror(stream: PointerLike) -> int: - return binding_base(dll.ferror, stream) - - -def fflush(stream: PointerLike) -> int: - return binding_base(dll.fflush, stream) - - -def fgetpos(stream: PointerLike, pos: PointerLike) -> int: - return binding_base(dll.fgetpos, stream, pos) - - -def fopen(filename: StringLike, mode: StringLike) -> VoidPointer: - return binding_base( - dll.fopen, - make_string(filename), - make_string(mode), - ) - - -def fread( - ptr: PointerLike, - size: int, - nmemb: int, - stream: PointerLike, -) -> int: - return binding_base(dll.fread, ptr, size, nmemb, stream) - - -def freopen( - filename: StringLike, - mode: StringLike, - stream: PointerLike, -) -> VoidPointer: - return binding_base( - dll.freopen, - make_string(filename), - make_string(mode), - stream, - ) - - -def fseek(stream: PointerLike, offset: int, whence: int) -> int: - return binding_base(dll.fseek, stream, offset, whence) - - -def fsetpos(stream: PointerLike, pos: PointerLike) -> int: - return binding_base(dll.fsetpos, stream, pos) - - -def ftell(stream: PointerLike) -> int: - return binding_base(dll.ftell, stream) - - -def fwrite( - ptr: PointerLike, - size: int, - nmemb: int, - stream: PointerLike, -) -> int: - return binding_base(dll.fwrite, ptr, size, nmemb, stream) - - -def remove(filename: StringLike) -> int: - return binding_base(dll.remove, make_string(filename)) - - -def rename(old_filename: StringLike, new_filename: StringLike) -> int: - return binding_base( - dll.rename, - make_string(old_filename), - make_string(new_filename), - ) - - -def rewind(stream: PointerLike) -> None: - return binding_base(dll.rewind, stream) - - -def setbuf(stream: PointerLike, buffer: StringLike) -> None: - return binding_base(dll.setbuf, stream, make_string(buffer)) - - -def setvbuf( - stream: PointerLike, - buffer: str, - mode: int, - size: int, -) -> int: - return binding_base( - dll.setvbuf, - stream, - make_string(buffer), - mode, - size, - ) - - -def tmpfile() -> VoidPointer: - return binding_base(dll.tmpfile) - - -def tmpnam(string: str) -> str: - return binding_base(dll.tmpnam, make_string(string)) - - -def fprintf(stream: PointerLike, fmt: StringLike, *args: Format) -> int: - return binding_base( - dll.fprintf, - stream, - make_string(fmt), - *make_format(*args), - ) - - -def printf(fmt: StringLike, *args: Format) -> int: - return binding_base(dll.printf, make_string(fmt), *make_format(*args)) - - -def sprintf(string: StringLike, fmt: StringLike, *args: Format) -> int: - return binding_base( - dll.sprintf, - make_string(string), - make_string(fmt), - *make_format(*args), - ) - - -def fscanf(stream: PointerLike, fmt: StringLike, *args: Format) -> int: - return binding_base( - dll.fscanf, - stream, - make_string(fmt), - *make_format(*args), - ) - - -def scanf(fmt: StringLike, *args: Format) -> int: - return binding_base(dll.scanf, make_string(fmt), *make_format(*args)) - - -def sscanf(string: StringLike, fmt: StringLike, *args: Format) -> int: - return binding_base( - dll.sscanf, - make_string(string), - make_string(fmt), - *make_format(*args), - ) - - -def fgetc(stream: PointerLike) -> int: - return binding_base(dll.fgetc, stream) - - -def fgets(string: StringLike, n: int, stream: PointerLike) -> str: - return binding_base( - dll.fgets, - make_string(string), - n, - stream, - ) - - -def fputc(char: int, stream: PointerLike) -> int: - return binding_base(dll.fputc, char, stream) - - -def fputs(string: StringLike, stream: PointerLike) -> int: - return binding_base(dll.fputs, make_string(string), stream) - - -def getc(stream: PointerLike) -> int: - return binding_base(dll.getc, stream) - - -def getchar() -> int: - return binding_base(dll.getchar) - - -def gets(string: StringLike) -> str: - return binding_base(dll.gets, make_string(string)) - - -def putc(char: int, stream: PointerLike) -> int: - return binding_base(dll.putc, char, stream) - - -def putchar(char: int) -> int: - return binding_base(dll.putchar, char) - - -def puts(string: StringLike) -> int: - return binding_base(dll.puts, make_string(string)) - - -def ungetc(char: int, stream: PointerLike) -> int: - return binding_base(dll.ungetc, char, stream) - - -def perror(string: StringLike) -> None: - return binding_base(dll.perror, make_string(string)) - - -def strtod(string: StringLike, endptr: PointerLike) -> int: - return binding_base(dll.strtod, make_string(string), endptr) - - -def strtol( - string: StringLike, - endptr: PointerLike, - base: int, -) -> int: - return binding_base( - dll.strtol, - make_string(string), - endptr, - base, - ) - - -def strtoul( - string: StringLike, - endptr: PointerLike, - base: int, -) -> int: - return binding_base( - dll.strtoul, - make_string(string), - endptr, - base, - ) - - -def abort() -> None: - return binding_base(dll.abort) - - -def exit(status: int) -> None: - return binding_base(dll.exit, status) - - -def getenv(name: StringLike) -> str: - return binding_base(dll.getenv, make_string(name)) - - -def system(string: StringLike) -> int: - return binding_base(dll.system, make_string(string)) - - -def abs(x: int) -> int: - return binding_base(dll.abs, x) - - -def labs(x: int) -> int: - return binding_base(dll.labs, x) - - -def rand() -> int: - return binding_base(dll.rand) - - -def srand(seed: int) -> None: - return binding_base(dll.srand, seed) - - -def mblen(string: StringLike, n: int) -> int: - return binding_base( - dll.mblen, - make_string(string), - n, - ) - - -def mbstowcs(pwcs: StringLike, string: StringLike, n: int) -> int: - return binding_base( - dll.mbstowcs, - pwcs, - make_string(string), - n, - ) - - -def mbtowc(pwc: StringLike, string: StringLike, n: int) -> int: - return binding_base( - dll.mbtowc, - pwc, - make_string(string), - n, - ) - - -def wcstombs(string: StringLike, pwcs: str, n: int) -> int: - return binding_base(dll.wcstombs, make_string(string), pwcs, n) - - -def wctomb(string: StringLike, wchar: str) -> int: - return binding_base(dll.wctomb, make_string(string), wchar) - - -def memchr(string: PointerLike, c: int, n: int) -> VoidPointer: - return binding_base(dll.memchr, string, c, n) - - -def memcmp( - str1: PointerLike, - str2: PointerLike, - n: int, -) -> int: - return binding_base(dll.memcmp, str1, str2, n) - - -def memcpy( - dest: PointerLike, - src: PointerLike, - n: int, -) -> VoidPointer: - return binding_base(dll.memcpy, dest, src, n) - - -def memmove( - dest: PointerLike, - src: PointerLike, - n: int, -) -> VoidPointer: - return binding_base(dll.memmove, dest, src, n) - - -def memset(string: PointerLike, c: int, n: int) -> VoidPointer: - return binding_base(dll.memset, string, c, n) - - -def strcat(dest: StringLike, src: StringLike) -> str: - return binding_base( - dll.strcat, - make_string(dest), - make_string(src), - ) - - -def strncat(dest: StringLike, src: StringLike, n: int) -> str: - return binding_base( - dll.strncat, - make_string(dest), - make_string(src), - n, - ) - - -def strchr(string: StringLike, c: int) -> str: - return binding_base(dll.strchr, make_string(string), c) - - -def strcmp(str1: StringLike, str2: StringLike) -> int: - return binding_base( - dll.strcmp, - make_string(str1), - make_string(str2), - ) - - -def strncmp(str1: StringLike, str2: StringLike, n: int) -> int: - return binding_base( - dll.strncmp, - make_string(str1), - make_string(str2), - n, - ) - - -def strcoll(str1: StringLike, str2: StringLike) -> int: - return binding_base( - dll.strcoll, - make_string(str1), - make_string(str2), - ) - - -def strcpy(dest: StringLike, src: StringLike) -> str: - return binding_base( - dll.strcpy, - make_string(dest), - make_string(src), - ) - - -def strncpy(dest: StringLike, src: StringLike, n: int) -> str: - return binding_base( - dll.strncpy, - make_string(dest), - make_string(src), - n, - ) - - -def strcspn(str1: StringLike, str2: StringLike) -> int: - return binding_base( - dll.strcspn, - make_string(str1), - make_string(str2), - ) - - -def strerror(errnum: int) -> str: - return binding_base(dll.strerror, errnum) - - -def strlen(string: StringLike) -> int: - return binding_base(dll.strlen, make_string(string)) - - -def strpbrk(str1: StringLike, str2: StringLike) -> str: - return binding_base( - dll.strpbrk, - make_string(str1), - make_string(str2), - ) - - -def strrchr(string: StringLike, c: int) -> str: - return binding_base(dll.strrchr, make_string(string), c) - - -def strspn(str1: StringLike, str2: StringLike) -> int: - return binding_base( - dll.strspn, - make_string(str1), - make_string(str2), - ) - - -def strstr(haystack: StringLike, needle: StringLike) -> str: - return binding_base( - dll.strstr, - make_string(haystack), - make_string(needle), - ) - - -def strtok(string: StringLike, delim: StringLike) -> str: - return binding_base( - dll.strtok, - make_string(string), - make_string(delim), - ) - - -def strxfrm(dest: StringLike, src: StringLike, n: int) -> int: - return binding_base( - dll.strxfrm, - make_string(dest), - make_string(src), - n, - ) - - -def asctime(timeptr: StructPointer[Tm]) -> str: - return binding_base(dll.asctime, timeptr) - - -def clock() -> int: - return binding_base(dll.clock) - - -def ctime(timer: TypedPtr[int]) -> str: - return binding_base(dll.ctime, timer) - - -def difftime(time1: int, time2: int) -> int: - return binding_base(dll.difftime, time1, time2) - - -def mktime(timeptr: StructPointer[Tm]) -> int: - return binding_base(dll.mktime, timeptr) - - -def strftime( - string: StringLike, - maxsize: int, - fmt: StringLike, - timeptr: StructPointer[Tm], -) -> int: - return binding_base( - dll.strftime, - make_string(string), - maxsize, - make_string(fmt), - timeptr, - ) - - -def time(timer: TypedPtr[int]) -> int: - return binding_base(dll.time, timer) - - -def div(numer: int, denom: int) -> DivT: - return binding_base(dll.div, numer, denom) - - -def ldiv(numer: int, denom: int) -> LDivT: - return binding_base(dll.ldiv, numer, denom) - - -def localeconv() -> StructPointer[Lconv]: - return binding_base(dll.localeconv) - - -def c_raise(sig: int) -> int: - return binding_base(ct_raise, sig) - - -def c_malloc(size: int) -> VoidPointer: - return binding_base(_malloc, size) - - -def c_calloc(items: int, size: int) -> VoidPointer: - return binding_base(_calloc, items, size) - - -def c_realloc(ptr: PointerLike, size: int) -> VoidPointer: - return binding_base(_realloc, ptr, size) - - -def c_free(ptr: PointerLike) -> None: - return binding_base(_free, ptr) - - -def gmtime(timer: PointerLike) -> StructPointer[Tm]: - return binding_base(dll.gmtime, timer) - - -def signal(signum: int, func: Callable[[int], Any]) -> None: - return binding_base(dll.signal, signum, func) - - -def qsort( - base: PointerLike, - nitem: int, - size: int, - compar: Callable[ - [Any, Any], - int, - ], -) -> None: - return binding_base(dll.qsort, base, nitem, size, compar) - - -def bsearch( - key: PointerLike, - base: PointerLike, - nitems: int, - size: int, - compar: Callable[ - [Any, Any], - int, - ], -) -> VoidPointer: - return binding_base(dll.bsearch, key, base, nitems, size, compar) - - -def sizeof(obj: Any) -> int: - try: - return ctypes.sizeof(obj) - except TypeError: - return ctypes.sizeof(get_mapped(obj)) diff --git a/src/pointers/c_pointer.py b/src/pointers/c_pointer.py deleted file mode 100644 index 98b5070..0000000 --- a/src/pointers/c_pointer.py +++ /dev/null @@ -1,303 +0,0 @@ -from __future__ import annotations - -import ctypes -from abc import ABC, abstractmethod -from typing import (TYPE_CHECKING, Any, Callable, Iterator, List, Optional, - Type, TypeVar) - -from _pointers import add_ref, remove_ref -from typing_extensions import ParamSpec - -from ._utils import deref, get_mapped, map_type -from .base_pointers import BaseCPointer, IterDereferencable -from .util import handle - -if TYPE_CHECKING: - from .structure import Struct, StructPointer - -T = TypeVar("T") -A = TypeVar("A", bound="Struct") -P = ParamSpec("P") - -__all__ = ( - "TypedCPointer", - "VoidPointer", - "to_c_ptr", - "cast", - "to_voidp", - "array", - "to_struct_ptr", - "to_func_ptr", -) - - -class VoidPointer(BaseCPointer[Any]): - """Class representing a void pointer to a C object.""" - - @property - def size(self) -> int: - return self._size - - @property # type: ignore - @handle - def _as_parameter_(self) -> ctypes.c_void_p: - return ctypes.c_void_p(self.address) - - @handle - def dereference(self) -> Optional[int]: - deref = ctypes.c_void_p.from_address(self.ensure()) - return deref.value - - def __repr__(self) -> str: - return f"VoidPointer(address={self.address}, size={self.size})" - - def _cleanup(self) -> None: - pass - - -class _CDeref(IterDereferencable[T], ABC): - @abstractmethod - def address(self) -> Optional[int]: - ... - - @property - @abstractmethod - def decref(self) -> bool: - """Whether the target objects reference count should be decremented when the pointer is garbage collected.""" # noqa - ... - - @handle - def _cleanup(self) -> None: - if self.address: - if (type(~self) is not str) and (self.decref): - remove_ref(~self) - - -class FunctionPointer(BaseCPointer[Callable[P, T]]): # type: ignore - def __init__(self, address: int) -> None: - cb = deref(address) - add_ref(cb) - self._decref = True - self._address = address - mapped: "ctypes._FuncPointer" = get_mapped(cb) # type: ignore - - @ctypes.CFUNCTYPE(mapped._restype_, *mapped._argtypes_) # type: ignore - def transport(*args, **kwargs): - cb(*args, **kwargs) - - add_ref(transport) - self._transport = transport - self._size = ctypes.sizeof(transport) - - @handle - def _cleanup(self) -> None: - if self.address: - remove_ref(~self) - remove_ref(self._transport) - - @property - def _as_parameter_(self) -> "ctypes._CData": - return self._transport - - @property - def size(self) -> int: - return self._size - - @property - def type(self) -> Type[Callable[P, T]]: - return type(~self) - - @handle - def dereference(self) -> Callable[P, T]: - return deref(self.ensure()) - - @handle # type: ignore - def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T: - return (~self)(*args, **kwargs) - - def __repr__(self) -> str: - return f"FunctionPointer(address={self.address})" - - -class TypedCPointer(_CDeref[T], BaseCPointer[T]): - """Class representing a pointer with a known type.""" - - def __init__( - self, - address: int, - data_type: Type[T], - size: int, - void_p: bool = True, - decref: bool = True, - alt: bool = False, - ) -> None: - self._void_p = void_p - super().__init__(address, size) - self._type = data_type - self._decref = decref - self.alt = alt - - @property - def size(self) -> int: - return self._size - - @property - def decref(self) -> bool: - return self._decref - - @property - def type(self): - return self._type - - @property - def address(self) -> Optional[int]: - return self._address - - @property # type: ignore - @handle - def _as_parameter_(self) -> ctypes._CData: - ctype = get_mapped(self.type) - - if (ctype is ctypes.c_char_p) and (self.alt): - deref = ctype(self.ensure()) - return deref - else: - deref = ctype.from_address(self.ensure()) - - value = deref.value # type: ignore - - if isinstance(value, (TypedCPointer, VoidPointer)): - return ctypes.pointer(value._as_parameter_) # type: ignore - - return ctypes.pointer(deref) - - @handle - def dereference(self) -> T: - """Dereference the pointer.""" - ctype = get_mapped(self.type) - - if (ctype is ctypes.c_char_p) and (self.alt): - res = ctypes.c_char_p(self.ensure()).value - return res # type: ignore - - ptr = ( - ctype.from_address(self.ensure()) - if not self._void_p - else ctypes.cast( - ctypes.c_void_p(self.address), ctypes.POINTER(ctype) - ) # fmt: off - ) - return ptr.value if not self._void_p else ptr.contents.value # type: ignore # noqa - - def __iter__(self) -> Iterator[T]: - """Dereference the pointer.""" - return iter({self.dereference()}) - - def __repr__(self) -> str: - return f"TypedCPointer(address={self.address}, size={self.size})" - - -class CArrayPointer(_CDeref[List[T]], BaseCPointer[List[T]]): - """Class representing a pointer to a C array.""" - - def __init__( - self, - address: int, - size: int, - length: int, - typ: Type[T], - ): - self._length = length - self._type = typ - self._decref = False - super().__init__(address, size) - - @property - def decref(self) -> bool: - return self._decref - - @property - @handle - def _as_parameter_(self) -> "ctypes.Array[ctypes._CData]": - ctype = get_mapped(self._type) - - deref = (ctype * self._length).from_address(self.ensure()) - return deref - - @handle - def dereference(self) -> List[T]: - """Dereference the pointer.""" - array = self._as_parameter_ - return [array[i] for i in range(self._length)] # type: ignore - - def __repr__(self) -> str: - return f"CArrayPointer(address={self.address}, size={self.size})" - - def __getitem__(self, index: int) -> T: - array = ~self - return array[index] - - -@handle -def cast(ptr: VoidPointer, data_type: Type[T]) -> TypedCPointer[T]: - """Cast a void pointer to a typed pointer.""" - - return TypedCPointer( - ptr.ensure(), - data_type, - ptr.size, - decref=False, - void_p=True, - alt=True, - ) - - -def to_voidp(ptr: TypedCPointer[Any]) -> VoidPointer: - """Cast a typed pointer to a void pointer.""" - - return VoidPointer(ptr.ensure(), ptr.size) - - -def to_c_ptr(data: T) -> TypedCPointer[T]: - """Convert a python type to a pointer to a C type.""" - ct = map_type(data) - - add_ref(ct) - address = ctypes.addressof(ct) - typ = type(data) - - return TypedCPointer(address, typ, ctypes.sizeof(ct), False) - - -def to_struct_ptr(struct: A) -> "StructPointer[A]": - """Convert a struct to a pointer.""" - from .structure import StructPointer - - return StructPointer(id(struct)) - - -@handle -def array(*seq: T) -> CArrayPointer[T]: - f_type = type(seq[0]) - - for i in seq: - if type(i) is not f_type: # dont use isinstance here - raise ValueError( - "all values in the array must be the same type", - ) - - length = len(seq) - ctype = get_mapped(f_type) - arr = (ctype * length)(*seq) # type: ignore - add_ref(arr) - - return CArrayPointer( - ctypes.addressof(arr), - ctypes.sizeof(arr), - length, - f_type, # type: ignore - ) - - -def to_func_ptr(fn: Callable[P, T]) -> FunctionPointer[P, T]: - return FunctionPointer(id(fn)) # type: ignore diff --git a/src/pointers/calloc.py b/src/pointers/calloc.py deleted file mode 100644 index 390f1af..0000000 --- a/src/pointers/calloc.py +++ /dev/null @@ -1,132 +0,0 @@ -from typing import Dict, Iterator, Optional, TypeVar - -from ._cstd import c_calloc, c_free -from .exceptions import AllocationError, DereferenceError -from .util import handle -from .base_pointers import BaseAllocatedPointer - -__all__ = ("AllocatedArrayPointer", "calloc") - -T = TypeVar("T") - - -# FOR FUTURE REFERENCE: - -# _chunk_store is needed to hold each index in the pointer array accordingly. -# We can't just lookup each index via a memory offset, -# since we can't verify that the memory actually contains something. - -# If the memory is empty, then Python will segfault as it can't convert it to -# a PyObject*. - - -# TODO: make this implementation better - - -class AllocatedArrayPointer(BaseAllocatedPointer[T]): - """Pointer to an allocated array.""" - - def __init__( - self, - address: int, - chunks: int, - chunk_size: int, - current_index: int, - chunk_store: Optional[Dict[int, "AllocatedArrayPointer[T]"]] = None, - freed: bool = False, - origin_address: Optional[int] = None, - ) -> None: - self._origin_address = origin_address or address - self._address = address - self._size = chunk_size - self._current_index = current_index - self._chunks = chunks - self._chunk_store = chunk_store or {0: self} - self._assigned = True - self._tracked = False - self._freed = freed - - if chunk_store: - self._chunk_store[self.current_index] = self - - @property # type: ignore - def address(self) -> Optional[int]: - return self._address - - @property - def current_index(self) -> int: - """Current chunk index.""" - return self._current_index - - @property - def chunks(self) -> int: - """Number of allocated chunks.""" - return self._chunks - - def _get_chunk_at(self, index: int) -> "AllocatedArrayPointer[T]": - if index > self.chunks: - raise IndexError( - f"index is {index}, while allocation is {self.chunks}", - ) - - if index < 0: # for handling __sub__ - raise IndexError("index is below zero") - - if index not in self._chunk_store: - self._chunk_store[index] = AllocatedArrayPointer( - self._origin_address + (index * self.size), - self.chunks, - self.size, - index, - self._chunk_store, - self._freed, - self._origin_address, - ) - - return self._chunk_store[index] - - def __add__(self, amount: int) -> "AllocatedArrayPointer[T]": - self.ensure_valid() - return self._get_chunk_at(self._current_index + amount) - - def __sub__(self, amount: int) -> "AllocatedArrayPointer[T]": - return self.__add__(-amount) - - def __repr__(self) -> str: - return f"AllocatedArrayPointer(address={self.address}, current_index={self.current_index})" # noqa - - def __iter__(self) -> Iterator["AllocatedArrayPointer[T]"]: - for i in range(self.current_index, self.chunks): - yield self + i - - def __getitem__(self, index: int) -> "AllocatedArrayPointer[T]": - return self._get_chunk_at(index) - - def __setitem__(self, index: int, value: T) -> None: - chunk = self._get_chunk_at(index) - chunk <<= value - - @property - def freed(self) -> bool: - return self._freed - - @handle - def free(self) -> None: - first = self[0] - first.ensure_valid() - - for i in range(self._chunks): # using __iter__ breaks here - chunk = self._get_chunk_at(i) - chunk._freed = True - - c_free(first.make_ct_pointer()) - - -def calloc(num: int, size: int) -> AllocatedArrayPointer: - """Allocate a number of blocks with a given size.""" - address: int = c_calloc(num, size) - - if not address: - raise AllocationError("failed to allocate memory") - - return AllocatedArrayPointer(address, num, size, 0) diff --git a/src/pointers/custom_binding.py b/src/pointers/custom_binding.py deleted file mode 100644 index 2443185..0000000 --- a/src/pointers/custom_binding.py +++ /dev/null @@ -1,71 +0,0 @@ -import ctypes -from functools import wraps -from typing import TYPE_CHECKING, Any, Callable, Optional, Type, TypeVar - -from typing_extensions import ParamSpec - -from .bindings import binding_base, make_string - -if TYPE_CHECKING: - from ctypes import _NamedFuncPointer - - from .structure import Struct - -T = TypeVar("T") -P = ParamSpec("P") - -__all__ = ("binds", "binding") - - -def binds( - dll_func: "_NamedFuncPointer", - *, - struct: Optional[Type["Struct"]] = None, -): - def decorator(func: Callable[P, T]) -> Callable[P, T]: - @wraps(func) - def wrapper(*args: P.args, **kwargs: P.kwargs) -> T: - if kwargs: - raise ValueError( - "keyword arguments are not allowed when calling C functions" # noqa - ) - - restype = dll_func.restype - - if ( - struct - and (not issubclass(restype, ctypes.Structure)) # type: ignore - and (not (restype or int).__name__.startswith("LP_")) - ): - raise ValueError("restype must be a ctypes structure") - - return binding_base( - dll_func, - *[ - # fmt: off - i if not isinstance(i, str) - else make_string(i) - # fmt: on - for i in args # type: ignore - ], - map_extra={ - dll_func.restype: struct, # type: ignore - } - if struct - else None, - ) - - return wrapper - - return decorator - - -def binding( - dll_func: "_NamedFuncPointer", - struct: Optional[Type["Struct"]] = None, -): - @binds(dll_func, struct=struct) - def wrapper(*args, **kwargs) -> Any: - ... - - return wrapper diff --git a/src/pointers/decay.py b/src/pointers/decay.py deleted file mode 100644 index 46582e9..0000000 --- a/src/pointers/decay.py +++ /dev/null @@ -1,124 +0,0 @@ -import inspect -from contextlib import suppress -from functools import wraps -from typing import Any, Callable, Dict, Tuple, TypeVar - -from typing_extensions import Annotated, ParamSpec, get_args, get_origin, get_type_hints - -from .object_pointer import Pointer, to_ptr - -T = TypeVar("T") -P = ParamSpec("P") - -__all__ = ("decay", "decay_annotated", "decay_wrapped") - - -def _make_func_params( - func: Callable[P, Any], - args: Tuple[Any, ...], - kwargs: Dict[str, Any], -) -> Tuple[Dict[str, Any], Dict[str, Any]]: - hints = get_type_hints(func, include_extras=True) - actual: dict = {} - params = inspect.signature(func).parameters - - for index, key in enumerate(params): - if key in kwargs: - actual[key] = kwargs[key] - else: - with suppress(IndexError): - actual[params[key].name] = args[index] - - return (hints, actual) - - -def _decay_params( - func: Callable[..., Any], - args: Tuple[Any, ...], - kwargs: Dict[str, Any], -) -> Dict[str, Any]: - hints, actual = _make_func_params(func, args, kwargs) - - for key, value in hints.items(): - if (get_origin(value) is Pointer) or (value is Pointer): - actual[key] = to_ptr(actual[key]) - - return actual - - -def decay(func: Callable[P, T]) -> Callable[..., T]: - """Automatically convert values to pointers when called. - - Example: - ```py - @decay - def my_function(a: str, b: Pointer[str]): - print(a, *c) - - my_function('a', 'b') - ``` - """ - - @wraps(func) - def inner(*args: P.args, **kwargs: P.kwargs) -> T: - actual = _decay_params(func, args, kwargs) - return func(**actual) # type: ignore - - return inner - - -def decay_annotated(func: Callable[P, T]) -> Callable[P, T]: - """ - Example: - ```py - @decay_annotated - def my_function(a: str, b: Annotated[str, Pointer]): - print(a, *c) - - my_function('a', 'b') - ``` - """ - - @wraps(func) - def wrapped(*args: P.args, **kwargs: P.kwargs): - hints, actual = _make_func_params(func, args, kwargs) - - for param, hint in hints.items(): - if get_origin(hint) is not Annotated: - continue - - hint_arg = get_args(hint)[1] - - if (hint_arg is Pointer) or (get_origin(hint_arg) is Pointer): - actual[param] = to_ptr(actual[param]) - - return func(**actual) # type: ignore - - return wrapped - - -def decay_wrapped(_: Callable[P, T]) -> Callable[..., Callable[P, T]]: - """ - Example: - ```py - def my_function_wrapper(a: str, b: str, c: str) -> None: - ... - - @decay_wrapped(my_function_wrapper) - def my_function(a: str, b: str, c: Pointer[str]): - print(a, b, *c) - print(a, b, ~c) - - my_function('a', 'b', 'c') - ``` - """ - - def decorator(func: Callable[..., T]) -> Callable[P, T]: - @wraps(func) - def wrapped(*args: P.args, **kwargs: P.kwargs): - actual = _decay_params(func, args, kwargs) - return func(**actual) - - return wrapped - - return decorator # type: ignore diff --git a/src/pointers/exceptions.py b/src/pointers/exceptions.py index 4addd0e..87db81d 100644 --- a/src/pointers/exceptions.py +++ b/src/pointers/exceptions.py @@ -1,47 +1,10 @@ -__all__ = ( - "AllocationError", - "DereferenceError", - "FreedMemoryError", - "InvalidSizeError", - "InvalidBindingParameter", - "NullPointerError", - "InvalidVersionError", - "SegmentViolation", - "VariableLifetimeError", -) - - -class AllocationError(Exception): - """Raised when a memory allocation fails.""" - - -class DereferenceError(Exception): - """Raised when dereferencing an address fails.""" # noqa - - -class FreedMemoryError(Exception): - """Raised when trying to perform an operation on freed memory.""" - - -class InvalidSizeError(Exception): - """Raised when trying to move an object of the wrong size to an allocation.""" # noqa - - -class InvalidBindingParameter(Exception): - """Raised when an invalid type is passed to a binding.""" - - -class NullPointerError(Exception): - """Raised when a pointer is null.""" - - -class InvalidVersionError(Exception): - """Python version is not high enough.""" - - -class SegmentViolation(Exception): - """SIGSEGV was sent to Python.""" - - -class VariableLifetimeError(Exception): - """Variable is no longer available.""" +class CompatibilityError(Exception): + """ + Something doesn't work on this Python version. + """ + + +class BufferOverflowError(Exception): + """ + Memory buffer will overflow. + """ diff --git a/src/pointers/magic.py b/src/pointers/magic.py deleted file mode 100644 index a7b70e2..0000000 --- a/src/pointers/magic.py +++ /dev/null @@ -1,22 +0,0 @@ -from typing import TYPE_CHECKING, TypeVar - -if TYPE_CHECKING: - from .base_pointers import BasePointer - from .object_pointer import Pointer - -from .object_pointer import to_ptr - -__all__ = ("_",) - -T = TypeVar("T") - - -class _PointerOperatorMagic: - def __and__(self, obj: T) -> "Pointer[T]": - return to_ptr(obj) - - def __mul__(self, ptr: "BasePointer[T]") -> T: - return ~ptr - - -_ = _PointerOperatorMagic() diff --git a/src/pointers/malloc.py b/src/pointers/malloc.py deleted file mode 100644 index a4906ac..0000000 --- a/src/pointers/malloc.py +++ /dev/null @@ -1,185 +0,0 @@ -from __future__ import annotations - -import sys -from typing import Any, Optional, TypeVar - -from ._cstd import c_free, c_malloc, c_realloc -from .base_pointers import BaseAllocatedPointer, IterDereferencable -from .exceptions import AllocationError, InvalidSizeError -from .stack_pointer import StackAllocatedPointer -from .util import handle - -__all__ = ("AllocatedPointer", "malloc", "free", "realloc") - - -T = TypeVar("T") -A = TypeVar("A", bound=BaseAllocatedPointer) - - -class AllocatedPointer(IterDereferencable[T], BaseAllocatedPointer[T]): - """Pointer to allocated memory.""" - - def __init__( - self, - address: int, - size: int, - assigned: bool = False, - parent: AllocatedPointer[T] | None = None, - ) -> None: - """ - Args: - address: Address of the allocated memory. - size: Size of the allocated memory. - assigned: Whether an object is currently inside the memory. - """ - self._address = address - self._size = size - self._freed = False - self._assigned = assigned - self._parent: AllocatedPointer[T] | None = parent - - def _indexed(self, amount: int) -> AllocatedPointer[T]: - return AllocatedPointer( - self.ensure() + amount, - self.size - amount, - self.assigned, - parent=self._parent, - ) - - def _get_parent(self) -> AllocatedPointer[T]: - parent = self - - while parent._parent: - parent = parent._parent - - return parent - - @property - def freed(self) -> bool: - return self._get_parent()._freed - - @freed.setter - def freed(self, value: bool) -> None: - self._get_parent()._freed = value - - @property - def address(self) -> Optional[int]: - return self._address - - @address.setter - def address(self, value: int) -> None: - self._address = value - - def __repr__(self) -> str: - return f"AllocatedPointer(address={self.address}, size={self.size})" - - def __add__(self, amount: int) -> AllocatedPointer[T]: - return self._indexed(amount) - - def __sub__(self, amount: int) -> AllocatedPointer[T]: - return self._indexed(amount) - - @handle - def free(self) -> None: - self.ensure_valid() - c_free(self.make_ct_pointer()) - self.freed = True - - @handle - def __getitem__(self, index: int) -> AllocatedPointer[T]: - if not isinstance(index, int): - raise ValueError( - f"memory indices must be int, not {type(index).__name__}", - ) - - return self._indexed(index) - - @handle - def __setitem__(self, index: int, value: T) -> None: - if not isinstance(index, int): - raise ValueError( - f"memory indices must be int, not {type(index).__name__}", - ) - - ptr = self._indexed(index) - ptr <<= value - - -def malloc(size: int) -> AllocatedPointer[Any]: - """Allocate memory of a given size. - - Args: - size: Allocation size. - - Returns: - Pointer to allocated memory. - - Raises: - AllocationError: Raised when allocation fails, presumably due to no memory. - - Example: - ```py - ptr = malloc(1) - ``` - """ # noqa - mem = c_malloc(size) - - if not mem: - raise AllocationError("failed to allocate memory") - - return AllocatedPointer(mem, size) - - -def free(target: BaseAllocatedPointer): - """Equivalent to `target.free()` - - Args: - target: Pointer to free. - - Example: - ```py - ptr = malloc(1) - free(ptr) # is the same as `ptr.free()` - ```""" - target.free() - - -@handle -def realloc(target: A, size: int) -> A: - """Resize a memory block created by malloc. - - Args: - target: Pointer to reallocate. - size: New allocation size. - - Returns: - Original object. - - Raises: - InvalidSizeError: Object inside allocation is larger than attempted reallocation. - AllocationError: Raised when allocation fails, presumably due to no memory. - - Example: - ```py - ptr = malloc(1) - realloc(ptr, 2) - ``` - """ # noqa - if type(target) is StackAllocatedPointer: - raise TypeError("pointers to items on the stack may not be resized") - - tsize: int = sys.getsizeof(~target) - - if target.assigned and (tsize > size): - raise InvalidSizeError( - f"object inside memory is of size {tsize}, so memory cannot be set to size {size}", # noqa - ) - - addr = c_realloc(target.address, size) - - if not addr: - raise AllocationError("failed to resize memory") - - target.size = size - target.address = addr - return target diff --git a/src/pointers/object_pointer.py b/src/pointers/object_pointer.py deleted file mode 100644 index c7313a1..0000000 --- a/src/pointers/object_pointer.py +++ /dev/null @@ -1,89 +0,0 @@ -import ctypes -import sys -from typing import TypeVar, Union - -from _pointers import add_ref, remove_ref, set_ref - -from .base_pointers import NULL, BaseObjectPointer, BasePointer, Nullable -from .exceptions import InvalidSizeError -from .util import handle - -T = TypeVar("T") - - -class Pointer(BaseObjectPointer[T]): - """Pointer to a `PyObject`""" - - def __repr__(self) -> str: - return f"Pointer(address={self.address})" - - @handle - def move( - self, - target: Union[T, "BasePointer[T]"], - *, - unsafe: bool = False, - ): - data = target if isinstance(target, BasePointer) else to_ptr(target) - - if not isinstance(data, BaseObjectPointer): - raise ValueError( - "pointer is not pointing to an object", - ) - - deref_a: T = ~data # type: ignore - deref_b: T = ~self - - size_a: int = sys.getsizeof(deref_a) - size_b: int = sys.getsizeof(deref_b) - refcnt = sys.getrefcount(deref_b) - refcnt_a = sys.getrefcount(deref_a) - - if (self._origin_size < size_a) and (not unsafe): - raise InvalidSizeError( - f"target size may not exceed current size ({size_a} < {size_b})", # noqa - ) - - if type(deref_a) is not type(deref_b): - raise TypeError( - "cannot move object of a different type", - ) - - current_address: int = self.ensure() - bytes_a = (ctypes.c_ubyte * size_a).from_address(data.ensure()) - bytes_b = (ctypes.c_ubyte * size_b).from_address(current_address) - - self.assign(~data) - ctypes.memmove(bytes_b, bytes_a, len(bytes_a)) - set_ref(deref_b, (refcnt - 1) + (refcnt_a - 2)) - - @classmethod - def make_from(cls, obj: Nullable[T]) -> "Pointer[T]": - is_null = obj is NULL - return Pointer( - id(obj) if not is_null else None, - not is_null, - ) - - -@handle -def to_ptr(obj: Nullable[T]) -> Pointer[T]: - """Point to the underlying `PyObject`. - - Args: - obj: Object to point to. - - Returns: - Created pointer. - - Example: - ```py - ptr = to_ptr(1) # ptr now points to 1 - something = 2 - something_ptr = to_ptr(something) # points to 2, not "something" - ``` - """ - add_ref(obj) - ptr = Pointer.make_from(obj) - remove_ref(obj) - return ptr diff --git a/src/pointers/pointer.py b/src/pointers/pointer.py new file mode 100644 index 0000000..52c263c --- /dev/null +++ b/src/pointers/pointer.py @@ -0,0 +1,159 @@ +from __future__ import annotations + +import ctypes +import sys +import weakref +from abc import ABC, abstractmethod +from typing import Generic, TypeVar, final + +from typing_extensions import Self + +from _pointers import decref, deref, getref, incref, setimmortal, setref + +from .exceptions import BufferOverflowError, CompatibilityError + +__all__ = "Pointer", "PyObjectPointer", "to_ptr", "BufferPointer" + +T = TypeVar("T") + + +class Pointer(ABC, Generic[T]): + """ + Base type used for all pointer objects. + """ + + address: int + """Memory address that the object is pointing to.""" + + @abstractmethod + def dereference(self) -> T: + """ + Dereference the pointer. + """ + + @final + def __invert__(self) -> T: + return self.dereference() + + @abstractmethod + def move(self, src: Self, *, allow_overflow: bool = False) -> None: + """ + Move the memory of `src` into this pointer. + """ + + @final + def __ilshift__(self, src: Self): + self.move(src) + + @final + def __ixor__(self, src: Self): + self.move(src, allow_overflow=True) + + def __repr__(self) -> str: + return f"<{type(self).__name__} to {hex(self.address)}>" + + __str__ = __repr__ + + +class BufferPointer(Pointer[bytes]): + def __init__( + self, + address: int, + size: int | None = None, + ) -> None: + self.address = address + self._size = size + + def dereference(self) -> bytes: + if self._size is not None: + return ctypes.string_at(self.address, size=self._size) + return ctypes.string_at(self.address) + + def size(self): + return len(~self) if self._size is None else self._size + + def _as_buffer(self) -> ctypes.Array[ctypes.c_ubyte]: + return (ctypes.c_ubyte * self.size()).from_address(self.address) + + def move( + self, src: BufferPointer, *, allow_overflow: bool = False + ) -> None: + src_size = src.size() + self_size = self.size() + + if (src_size > self_size) and (not allow_overflow): + raise BufferOverflowError( + f"{src} will overflow {src_size - self_size} bytes" + ) + + ctypes.memmove(self._as_buffer(), src._as_buffer(), src_size) + + +class PyObjectPointer(Pointer[T], Generic[T]): + """ + Type representing a pointer to a Python object. + """ + + def __init__(self, address: int) -> None: + self.address = address + self.refcount += 1 + weakref.finalize(self, self._cleanup) + + def _cleanup(self) -> None: + self.refcount -= 1 + + def size(self) -> int: + return sys.getsizeof(~self) + + def dereference(self) -> T: + return deref(self.address) + + @property + def refcount(self) -> int: + """ + The reference count of the underlying object. + """ + return getref(~self) + + @refcount.setter + def refcount(self, value: int) -> None: + setref(~self, value + 1) + + def immortalize(self) -> None: + """ + Turn the underlying object into a PEP 683 immortal object. + + On <3.12, this method raises a `CompatibilityError`. + """ + if sys.version_info >= (3, 12): + setimmortal(~self) + else: + raise CompatibilityError( + "immortal objects are not supported on this version", + ) + + def defer_refcount(self) -> None: + """ + Enable PEP 703 deferred reference counting on the object. + + If this is called on a build with the GIL enabled, this + raises a `CompatibilityError`. + """ + raise CompatibilityError( + "deferred reference counting is not supported", + ) + + def as_buffer(self) -> BufferPointer: + return BufferPointer(self.address, self.size()) + + def move(self, src: Self, *, allow_overflow: bool = False) -> None: + return self.as_buffer().move( + src.as_buffer(), allow_overflow=allow_overflow, + ) + + +def to_ptr(obj: T) -> PyObjectPointer[T]: + incref(obj) + ptr = PyObjectPointer(id(obj)) + decref(obj) + return ptr diff --git a/src/pointers/py.typed b/src/pointers/py.typed deleted file mode 100644 index e69de29..0000000 diff --git a/src/pointers/stack_pointer.py b/src/pointers/stack_pointer.py deleted file mode 100644 index c62c262..0000000 --- a/src/pointers/stack_pointer.py +++ /dev/null @@ -1,114 +0,0 @@ -from typing import Any, Callable, Optional, TypeVar - -from _pointers import run_stack_callback - -from .base_pointers import BaseAllocatedPointer, IterDereferencable -from .util import handle - -__all__ = ("StackAllocatedPointer", "acquire_stack_alloc", "stack_alloc") - - -T = TypeVar("T") -A = TypeVar("A", bound=BaseAllocatedPointer) - - -class StackAllocatedPointer(IterDereferencable[T], BaseAllocatedPointer[T]): - """Pointer to memory allocated on the stack.""" - - def __init__( - self, - address: int, - size: int, - assigned: bool = False, - ) -> None: - """ - Args: - address: Address of the allocated memory. - size: Size of the allocated memory. - assigned: Whether an object is currently inside the memory. - """ - self._address = address - self._size = size - self._freed = False - self._assigned = assigned - - @property - def freed(self) -> bool: - return self._freed - - @freed.setter - def freed(self, value: bool) -> None: - self._freed = value - - @property - def address(self) -> Optional[int]: - return self._address - - @address.setter - def address(self, value: int) -> None: - self._address = value - - def __repr__(self) -> str: - return f"StackAllocatedPointer(address={self.address}, size={self.size})" # noqa - - def __add__(self, amount: int): - return StackAllocatedPointer( - self.ensure() + amount, - self.size, - self.assigned, - ) - - def __sub__(self, amount: int): - return StackAllocatedPointer( - self.ensure() - amount, - self.size, - self.assigned, - ) - - def free(self) -> None: - raise ValueError( - "pointers to items on the stack may not be freed dynamically", - ) - - -@handle -def stack_alloc( - size: int, -) -> Callable[ - [Callable[[StackAllocatedPointer[Any]], T]], Callable[[], T] -]: # noqa - """Get a callback with a pointer to stack allocated memory. - This function **is not** run automatically. - For that purpose, use `acquire_stack_alloc`. - - Args: - size: Size of the allocation - """ - - def decorator( - func: Callable[[StackAllocatedPointer[Any]], T], - ) -> Callable[[], T]: - def wrapper(): - return run_stack_callback(size, StackAllocatedPointer, func) - - return wrapper - - return decorator - - -def acquire_stack_alloc( - size: int, -) -> Callable[[Callable[[StackAllocatedPointer[Any]], T]], T]: - """Execute a callback with a pointer to stack allocated memory. - - Args: - size: Size of the allocation - """ - - def decorator(func: Callable[[StackAllocatedPointer[Any]], T]) -> T: - def wrapper(): - return run_stack_callback(size, StackAllocatedPointer, func) - - return wrapper() - - return decorator diff --git a/src/pointers/std_structs.py b/src/pointers/std_structs.py deleted file mode 100644 index c9aaded..0000000 --- a/src/pointers/std_structs.py +++ /dev/null @@ -1,181 +0,0 @@ -import ctypes -from typing import Any, Callable, Dict, Type - -from ._cstd import div_t, lconv, ldiv_t, tm -from ._pyapi import ( - Py_buffer, - Py_tss_t, - PyCodeObject, - PyFrameObject, - PyGetSetDef, - PyInterpreterState, - PyMethodDef, - PyModuleDef, - PyThreadState, - PyType_Slot, - PyType_Spec, - PyTypeObject, - PyVarObject, -) -from .c_pointer import TypedCPointer, VoidPointer -from .structure import Struct, StructPointer -from .util import raw_type - -__all__ = ( - "Tm", - "DivT", - "LDivT", - "Lconv", - "PyTypeSlot", - "PyTypeSpec", - "Buffer", - "TypeObject", - "ThreadState", - "FrameObject", - "VarObject", - "ModuleDef", - "TssT", - "InterpreterState", - "CodeObject", - "MethodDef", - "GetSetDef", - "STRUCT_MAP", -) - - -class Tm(Struct): - tm_sec: int - tm_min: int - tm_hour: int - tm_mday: int - tm_mon: int - tm_year: int - tm_wday: int - tm_yday: int - tm_isdst: int - - -class DivT(Struct): - quot: int - rem: int - - -class LDivT(DivT): - pass - - -class Lconv(Struct): - decimal_point: bytes - thousands_sep: bytes - grouping: bytes - int_curr_symbol: bytes - currency_symbol: bytes - mon_decimal_point: bytes - mon_thousands_sep: bytes - mon_grouping: bytes - positive_sign: bytes - negative_sign: bytes - frac_digits: bytes - p_cs_precedes: bytes - p_sep_by_space: bytes - n_sep_by_space: bytes - p_sign_posn: bytes - n_sign_posn: bytes - - -class PyTypeSlot(Struct): - slot: int - pfunc: VoidPointer - - -class PyTypeSpec(Struct): - name: bytes - basic_size: int - itemsize: int - flags: int - slots: StructPointer[PyTypeSlot] - - -class Buffer(Struct): - buf: VoidPointer - obj: VoidPointer - len: int - readonly: int - itemsize: int - format: bytes - ndim: int - shape: TypedCPointer[int] = raw_type(ctypes.POINTER(ctypes.c_ssize_t)) - strides: TypedCPointer[int] = raw_type(ctypes.POINTER(ctypes.c_ssize_t)) - suboffsets: TypedCPointer[int] = raw_type(ctypes.POINTER(ctypes.c_ssize_t)) - internal: VoidPointer - - -class TypeObject(Struct): - __PYOBJECT__ = True - - -class ThreadState(Struct): - pass - - -class FrameObject(Struct): - __PYOBJECT__ = True - - -class VarObject(Struct): - ob_size: int = raw_type(ctypes.c_ssize_t) - ob_refcnt: int = raw_type(ctypes.c_ssize_t) - ob_type: StructPointer[TypeObject] - - -class ModuleDef(Struct): - m_base: bytes - pfunc: VoidPointer - - -class TssT(Struct): - pass - - -class InterpreterState(Struct): - pass - - -class CodeObject(Struct): - pass - - -class MethodDef(Struct): - ml_name: bytes - ml_meth: Callable[[Any], Any] - ml_flags: int - ml_doc: bytes - - -class GetSetDef(Struct): - name: bytes - get: Callable[[Any, VoidPointer], Any] - set: Callable[[Any, Any, VoidPointer], int] - doc: bytes - closure: VoidPointer - - -STRUCT_MAP: Dict[Type[ctypes.Structure], Type[Struct]] = { - tm: Tm, - div_t: DivT, - ldiv_t: LDivT, - lconv: Lconv, - PyType_Slot: PyTypeSlot, - PyType_Spec: PyTypeSpec, - Py_buffer: Buffer, - PyInterpreterState: InterpreterState, - PyModuleDef: ModuleDef, - Py_tss_t: TssT, - PyVarObject: VarObject, - PyFrameObject: FrameObject, - PyThreadState: ThreadState, - PyTypeObject: TypeObject, - PyCodeObject: CodeObject, - PyMethodDef: MethodDef, - PyGetSetDef: GetSetDef, -} diff --git a/src/pointers/structure.py b/src/pointers/structure.py deleted file mode 100644 index a33f3f1..0000000 --- a/src/pointers/structure.py +++ /dev/null @@ -1,211 +0,0 @@ -import ctypes -from contextlib import suppress -from typing import Any, Dict, List, Optional, Type, TypeVar, Union - -from _pointers import add_ref - -from ._utils import attempt_decode, get_mapped, get_py -from .base_pointers import BaseCPointer -from .c_pointer import TypedCPointer, VoidPointer -from .object_pointer import Pointer -from .util import RawType, handle - -T = TypeVar("T", bound="Struct") - -__all__ = ( - "Struct", - "StructPointer", -) - - -class Struct: - """Abstract class representing a struct.""" - - _hints: Dict[str, Any] - _void_p: List[str] - _internal_struct: Type[ctypes.Structure] - - @classmethod - def _convert_tc_ptr(cls, typ: Any, name: str): - if typ is TypedCPointer: - raise TypeError( - "cannot instantiate: TypedCPointer has no type argument", - ) - - if getattr(typ, "__origin__", None) is TypedCPointer: - setattr( - cls, - name, - RawType( - ctypes.POINTER(get_mapped(typ.__args__[0])), - ), - ) - - return typ - - @classmethod - def _get_type( - cls, - ct: Type["ctypes._CData"], - name: str, - ) -> Type["ctypes._CData"]: - attr = getattr(cls, name, None) - - if isinstance(attr, RawType): - return attr.tp - - if ct is ctypes.c_void_p: - cls._void_p.append(name) - - return ct - - def __init__(self, *args: Any, do_sync: bool = True): - class_typ: Type[Struct] = type(self) - - if class_typ is Struct: - raise Exception( - "cannot instantiate Struct directly", - ) - - self._existing_address: Optional[int] = None - self._struct = self._internal_struct( - *[ - i if not isinstance(i, BaseCPointer) else i._as_parameter_ - for i in args # fmt: off - ] - ) - - if do_sync: - self._sync() - - def __init_subclass__(cls): - hints = cls.__annotations__ - cls._void_p = [] - cls._hints = { - k: cls._convert_tc_ptr(v, k) - for k, v in hints.items() - if k not in {"_hints", "_void_p", "_internal_struct"} - } - - class _InternalStruct(ctypes.Structure): - _fields_ = [ - ( - name, - cls._get_type(get_mapped(typ), name), - ) - for name, typ in cls._hints.items() # fmt: off - ] - - cls._internal_struct = _InternalStruct - - @property - def _as_parameter_(self) -> ctypes.Structure: - return self._struct - - @classmethod - def from_existing(cls, struct: ctypes.Structure) -> "Struct": - """Build a new struct from an existing ctypes structure. - - Args: - struct: Existing `ctypes.Structure` object - - Returns: - Created struct object. - """ - instance = cls(do_sync=False) - instance._struct = struct # type: ignore - # mypy is getting angry here for whatever reason - instance._sync() - instance._existing_address = ctypes.addressof(struct) - - return instance - - @handle - def __getattribute__(self, name: str): - attr = super().__getattribute__(name) - - with suppress(AttributeError): - hints = super().__getattribute__("_hints") - - if (name in hints) and (type(attr)) is bytes: - attr = attempt_decode(attr) - - if isinstance(attr, ctypes._Pointer): # type: ignore - value = attr.contents - ct = type(value) - - if ct is ctypes.c_void_p: - add_ref(ct) - return VoidPointer( - ctypes.addressof(value), - ctypes.sizeof(value), - ) - - py_type = get_py(ct) - return TypedCPointer( - ctypes.addressof(value), - py_type, - ctypes.sizeof(value), - False, - ) - - if name in super().__getattribute__("_void_p"): - ct = ctypes.c_void_p(attr) # type: ignore - return VoidPointer(attr, ctypes.sizeof(ct)) # type: ignore - - return attr - - def __setattr__(self, name: str, value: Any): - if hasattr(self, "_struct"): - self._struct.__setattr__(name, value) - super().__setattr__(name, value) - - def _sync(self) -> None: - for name in self._hints: - setattr(self, name, getattr(self._struct, name)) - - def __repr__(self) -> str: - return f"<struct {type(self).__name__} at {hex(ctypes.addressof(self._struct))}>" # noqa - - @property - def struct(self) -> ctypes.Structure: - """Raw internal Structure object.""" - return self._struct - - def get_existing_address(self) -> int: - if not self._existing_address: - raise ValueError("instance has not been created from a C struct") - return self._existing_address - - -class StructPointer(Pointer[T]): - """Class representing a pointer to a struct.""" - - def __init__( - self, - address: int, - existing: Optional["Struct"] = None, - ): - self._existing = existing - super().__init__(address, True) - - @property # type: ignore - @handle - def _as_parameter_( - self, - ) -> Union[int, "ctypes._PointerLike"]: - existing = self._existing - - if existing: - return ctypes.pointer(existing.struct) - - return self.ensure() - - def __repr__(self) -> str: - return f"StructPointer(address={self.address}, existing={self._existing!r})" # noqa - - def __rich__(self) -> str: - return f"<[bold blue]pointer[/] to struct at {str(self)}>" - - def get_existing_address(self) -> int: - return (~self).get_existing_address() diff --git a/src/pointers/util.py b/src/pointers/util.py deleted file mode 100644 index 674d1c9..0000000 --- a/src/pointers/util.py +++ /dev/null @@ -1,94 +0,0 @@ -from __future__ import annotations -import ctypes -import faulthandler -from contextlib import suppress -from functools import wraps -from io import UnsupportedOperation -from typing import ( - TYPE_CHECKING, Any, Callable, NamedTuple, Type, TypeVar, Union -) -import os -from _pointers import handle as _handle -from typing_extensions import ParamSpec -from .exceptions import SegmentViolation - -if TYPE_CHECKING: - from .structure import Struct, StructPointer - -with suppress( - UnsupportedOperation -): # in case its running in idle or something like that - faulthandler.enable() - -__all__ = ( - "NULL", - "Nullable", - "raw_type", - "handle", - "struct_cast", - "stop_handler" -) - -T = TypeVar("T") -P = ParamSpec("P") - - -class NULL: - """Unique object representing a NULL address. - - May be used with object pointers or passed to bindings. - """ - - -Nullable = Union[T, Type[NULL]] - - -class RawType(NamedTuple): - tp: Type["ctypes._CData"] - - -def raw_type(ct: Type["ctypes._CData"]) -> Any: - """Set a raw ctypes type for a struct.""" - return RawType(ct) - - -def stop_handler() -> None: - """Shutoff the SIGSEGV handler.""" - os.environ["POINTERSPY_ALLOW_SEGV"] = "1" - -def handle(func: Callable[P, T]) -> Callable[P, T]: - """Handle segment violation errors when called.""" - - @wraps(func) - def wrapper(*args: P.args, **kwargs: P.kwargs) -> T: - try: - faulthandler.disable() - call = _handle(func, args, kwargs) - - with suppress(UnsupportedOperation): - faulthandler.enable() - - return call - except (RuntimeError, OSError) as e: - msg = str(e) - - if not any( - { - msg.startswith("segment violation"), - msg.startswith("exception: access violation"), - } - ): - raise - - with suppress(UnsupportedOperation): - faulthandler.enable() - - raise SegmentViolation(msg) from None - - return wrapper - - -@handle -def struct_cast(ptr: Union["Struct", "StructPointer"]) -> Any: - """Cast a `Struct` or `StructPointer` to a Python object.""" - return ctypes.cast(ptr.get_existing_address(), ctypes.py_object).value diff --git a/src/pointers/var_pointer.py b/src/pointers/var_pointer.py deleted file mode 100644 index a4d6905..0000000 --- a/src/pointers/var_pointer.py +++ /dev/null @@ -1,119 +0,0 @@ -import inspect -import warnings -from types import FrameType as Frame -from typing import Any, Dict, Optional, TypeVar, Union -from varname import nameof - -from _pointers import force_update_locals - -from .base_pointers import BasePointer -from .exceptions import NullPointerError, VariableLifetimeError -from .util import NULL, Nullable, handle - -__all__ = "VarPointer", "to_var_ptr" - -T = TypeVar("T") - -class VarPointer(BasePointer[T]): - def __init__(self, name: str, frame: Frame) -> None: - self.name: Optional[str] = name - self._frame = frame - self._address = id(~self) - - def _get_scope(self) -> Dict[str, Any]: - if not self.name: - raise NullPointerError("pointer is NULL") - - frame = self._frame - - if self.name in frame.f_globals: - return frame.f_globals - - if self.name in frame.f_locals: - return frame.f_locals - - raise VariableLifetimeError(f'variable "{self.name}" no longer exists') - - @handle - def move( - self, - target: Union[T, "BasePointer[T]"], - *, - unsafe: bool = False, - ) -> None: - if unsafe: - warnings.warn("unsafe has no effect on variable pointers") - - if not self.name: - raise NullPointerError("pointer is NULL") - - scope = self._get_scope() - - if (scope is self._frame.f_locals) and ( - self._frame.f_locals is not self._frame.f_globals - ): - force_update_locals( - self._frame, - self.name, - ( - ~target - if isinstance( - target, - BasePointer, - ) - else target - ), - ) - else: - scope[self.name] = ( - ~target - if isinstance( - target, - BasePointer, - ) - else target - ) - - @property - def address(self) -> Optional[int]: - return self._address - - def _cleanup(self) -> None: - pass - - def __repr__(self) -> str: - return f"VarPointer(name={self.name!r})" - - def dereference(self) -> T: - if not self.name: - raise NullPointerError("pointer is NULL") - - return self._get_scope()[self.name] - - def assign(self, value: Nullable[Union["VarPointer[T]", T]], *, frame: int = 2) -> None: - if value is NULL: - self._address = 0 - self.name = None - return - - fframe = inspect.currentframe() - assert fframe - assert fframe.f_back - - self.name = nameof(value, frame=frame) - self._address = id(value) - - def __irshift__( - self, - value: Nullable[Union["VarPointer[T]", T]], - ): - self.assign(value, frame=3) - return self - - -def to_var_ptr(value: T) -> VarPointer[T]: - frame = inspect.currentframe() - assert frame - assert frame.f_back - name = nameof(value, frame=2) - return VarPointer(name, frame.f_back) diff --git a/tests/test_allocation.py b/tests/test_allocation.py deleted file mode 100644 index ecc2d0a..0000000 --- a/tests/test_allocation.py +++ /dev/null @@ -1,135 +0,0 @@ -import sys - -from ward import raises, test - -from pointers import (DereferenceError, FreedMemoryError, InvalidSizeError, - StackAllocatedPointer, acquire_stack_alloc, calloc, free, - malloc, realloc) - - -@test("malloc and free") -def _(): - ptr = malloc(28) - assert ptr.freed is False - assert ptr.assigned is False - ptr <<= 1 - assert ptr.assigned is True - - with raises(InvalidSizeError): - ptr <<= "hello" - - free(ptr) - - with raises(FreedMemoryError): - print(~ptr) - - with raises(FreedMemoryError): - free(ptr) - - with raises(FreedMemoryError): - ptr.ensure_valid() - - assert ptr.freed is True - - -@test("calloc with enumerations") -def _(): - ptr = calloc(4, 28) - - for index, value in enumerate(ptr): - value <<= index + 1 - - assert [~i for i in ptr] == [1, 2, 3, 4] - - free(ptr) - - with raises(FreedMemoryError): - print(~ptr) - - -@test("calloc") -def _(): - if sys.version_info.minor >= 11: - return - ptr = calloc(4, 28) - assert ptr.chunks == 4 - - with raises(InvalidSizeError): - ptr <<= "hello" - - for index, value in enumerate(ptr): - value <<= index + 1 - - with raises(IndexError): - ptr -= 1 - - with raises(IndexError): - ptr += 10 - - assert ~ptr == 1 - ptr += 1 - assert ptr.current_index == 1 - assert ~ptr == 2 - - ptr[0] = 10 - assert ~ptr[0] == 10 - - free(ptr) - - with raises(FreedMemoryError): - ptr -= 1 - - with raises(FreedMemoryError): - ptr <<= "test" - - -@test("realloc") -def _(): - ptr = malloc(28) - ptr <<= 1 - - realloc(ptr, 30) - assert ~ptr == 1 - target: str = "hello world" - nptr = realloc(ptr, sys.getsizeof(target) + 1) - assert nptr is ptr - - ptr <<= target - assert ~ptr == target - - with raises(InvalidSizeError): - realloc(ptr, 10) - - -@test("allocation with tracked types") -def _(): - if sys.version_info.minor >= 11: - return - class A: - def __init__(self, value: str) -> None: - self.value = value - - obj = A("hello") - ptr = malloc(sys.getsizeof(obj)) - ptr <<= obj - - assert (~ptr).value == "hello" - free(ptr) - assert obj.value == "hello" - - -@test("stack allocation") -def _(): - @acquire_stack_alloc(28) - def cb(ptr: StackAllocatedPointer[int]): - assert type(ptr) is StackAllocatedPointer - - with raises(DereferenceError): - print(*ptr) - - ptr <<= 0 - - with raises(InvalidSizeError): - ptr <<= "hello" - - assert ~ptr == 0 diff --git a/tests/test_bindings.py b/tests/test_bindings.py deleted file mode 100644 index 3d94f5e..0000000 --- a/tests/test_bindings.py +++ /dev/null @@ -1,157 +0,0 @@ -from ward import raises, test - -from pointers import ( - InvalidBindingParameter, - Struct, - StructPointer, - TypedCPointer, - VoidPointer, -) -from pointers import _cstd as std -from pointers import ( - binds, - c_free, - c_malloc, - cast, - div, - isspace, - signal, - sprintf, - strcpy, - strlen, - to_c_ptr, - to_struct_ptr, - to_voidp, - toupper, -) -from pointers.std_structs import DivT - - -@test("c strings") -def _(): - ptr = c_malloc(2) - strcpy(ptr, "a") - assert ~cast(ptr, bytes) == b"a" - c_free(ptr) - - assert strlen(b"test") == 4 - - -@test("format strings") -def _(): - ptr = c_malloc(2) - sprintf(ptr, "%s", "a") - assert ~cast(ptr, bytes) == b"a" - c_free(ptr) - - -@test("argument validation") -def _(): - with raises(InvalidBindingParameter): - strlen(1) # type: ignore - - assert strlen("test") == 4 - - -@test("functions") -def _(): - def sighandler(signum: int): - ... - - def bad(signum: str): - ... - - signal(2, sighandler) - - with raises(InvalidBindingParameter): - signal(2, bad) # type: ignore - - signal(2, lambda x: ...) - - -@test("structs") -def _(): - res = div(10, 1) - assert type(res) is DivT - assert res.quot == 10 - - class A(Struct): - one: int - two: int - - a = A(1, 2) - - class MyStruct(Struct): - a: str - b: str - c: StructPointer[A] - d: TypedCPointer[int] - e: VoidPointer - - s = MyStruct( - "a", - "b", - to_struct_ptr(a), - to_c_ptr(1), - to_voidp( - to_c_ptr("hello"), - ), - ) - - assert s.a == "a" - assert type(s.c) is StructPointer - assert type(s.d) is TypedCPointer - assert type(s.e) is VoidPointer - - assert (~s.c) is a - assert (~s.c).one == a.one - assert ~s.d == 1 - assert ~cast(s.e, str) == "hello" - - with raises(TypeError): - - class Foo(Struct): - bar: TypedCPointer - - -@test("custom bindings") -def _(): - @binds(std.dll.strlen) - def strlen(a: str): - ... - - strlen("test") - - with raises(InvalidBindingParameter): - strlen(1) # type: ignore - - -@test("chars") -def _(): - assert toupper(97) == "A" - assert toupper("a") == "A" - - with raises(InvalidBindingParameter): - isspace("hi") - - with raises(InvalidBindingParameter): - isspace("") - - assert isspace(" ") != 0 - - -@test("c pointers") -def _(): - ptr = to_c_ptr(1) - ptr2 = to_c_ptr("hi") - - assert ~ptr == 1 - assert ~ptr2 == "hi" - - double_ptr = to_c_ptr(to_c_ptr(1)) - assert type(~double_ptr) is TypedCPointer - assert ~(~double_ptr) == 1 - voidp = to_voidp(to_c_ptr(1)) - assert type(voidp) is VoidPointer - - assert ~cast(voidp, int) == 1 diff --git a/tests/test_decay.py b/tests/test_decay.py deleted file mode 100644 index 73d5d91..0000000 --- a/tests/test_decay.py +++ /dev/null @@ -1,64 +0,0 @@ -from typing_extensions import Annotated -from ward import test - -from pointers import Pointer, decay, decay_annotated, decay_wrapped - - -@test("decay") -def _(): - @decay - def func(a: str, b: int, c: Pointer): - assert type(a) is str - assert type(b) is int - assert type(c) is Pointer - - func("a", 1, "c") - - @decay - def func2(a: str, b: int, c: Pointer[str]): - assert type(a) is str - assert type(b) is int - assert type(c) is Pointer - - func2("a", 1, "c") - - -@test("decay with annotated") -def _(): - @decay_annotated - def func(a: str, b: int, c: Annotated[str, Pointer]): - assert type(a) is str - assert type(b) is int - assert type(c) is Pointer - - func("a", 1, "c") - - @decay_annotated - def func2(a: str, b: int, c: Annotated[str, Pointer[str]]): - assert type(a) is str - assert type(b) is int - assert type(c) is Pointer - - func2("a", 1, "c") - - -@test("decay with wrapped") -def _(): - def wrapper(a: str, b: int, c: str) -> None: - ... - - @decay_wrapped(wrapper) - def func(a: str, b: int, c: Pointer): - assert type(a) is str - assert type(b) is int - assert type(c) is Pointer - - func("a", 1, "c") - - @decay_wrapped(wrapper) - def func2(a: str, b: int, c: Pointer[str]): - assert type(a) is str - assert type(b) is int - assert type(c) is Pointer - - func2("a", 1, "c") diff --git a/tests/test_pointer.py b/tests/test_pointer.py index a9dd71f..82f153e 100644 --- a/tests/test_pointer.py +++ b/tests/test_pointer.py @@ -1,88 +1,90 @@ -from ward import raises, test +import sys -from pointers import NULL, InvalidSizeError, Pointer -from pointers import _ as m -from pointers import to_c_ptr, to_ptr -from pointers.exceptions import NullPointerError +import pytest +from pointers import (BufferOverflowError, CompatibilityError, Pointer, + PyObjectPointer, to_ptr) -@test("creating pointers") -def _(): - assert type(to_ptr("a")) is Pointer - assert type(m & "a") is Pointer +def test_pointer_type(): + ptr = to_ptr("hello") + assert isinstance(ptr, Pointer) + assert isinstance(ptr, PyObjectPointer) -@test("dereferencing") -def _(): - ptr = to_ptr("test") - assert ~ptr == "test" - assert m * ptr == "test" - assert (*ptr,) == (~ptr,) - cptr = to_c_ptr("test") - assert ~cptr == "test" +def test_pointer_deref(): + x = "test" + ptr = to_ptr(x) + assert ptr.address == id(x) + assert (~ptr) == x -@test("assignment") -def _(): - ptr = to_ptr("test") - ptr.assign("a") - assert ~ptr == "a" - ptr >>= "test" - assert ~ptr == "test" +def test_pointer_tracked_type(): + ptr = to_ptr(object()) + assert ptr.refcount == 2 +def test_pointer_refcount(): + x = object() + ptr = to_ptr(x) + assert ptr.refcount == sys.getrefcount(x) -@test("movement") -def _(): - a = 763723 - ptr = to_ptr(a) - ptr <<= 2 + # ~ptr creates an extra reference, we need to account for it + assert ptr.refcount == (sys.getrefcount(~ptr) - 1) - assert a == 2 + before = sys.getrefcount(x) + ptr.refcount += 1 + assert (before + 1) == ptr.refcount + ptr.refcount -= 1 + assert before == ptr.refcount - with raises(InvalidSizeError): - ptr <<= 758347580937450893 +def test_size(): + x = "hello world" + assert to_ptr(x).size() == sys.getsizeof(x) -@test("assignment with tracked types") -def _(): - class A: - def __init__(self, value: str) -> None: - self.value = value + # This check is an implementation detail. + # If this doesn't work in the future, feel free to remove it. + assert to_ptr(object()).size() == sys.getsizeof(object()) - obj = A("hello") - ptr = to_ptr(A("world")) - assert (~ptr).value == "world" - ptr >>= obj - assert (~ptr).value == "hello" - ptr2 = to_ptr(obj) - ptr2 >>= A("12345") - assert (~ptr2).value == "12345" +def test_move_object(): + x = "do not touch this string ever again" + to_ptr(x).move(to_ptr("hello world")) + assert x == "hello world" + with pytest.raises(BufferOverflowError): + to_ptr("1").move(to_ptr("no good!")) -@test("null pointers") -def _(): - ptr = to_ptr(0) - ptr >>= NULL - with raises(NullPointerError): - print(~ptr) +def test_object_deallocation(): + called = False - with raises(NullPointerError): - print(*ptr) + class Tracked: + def __del__(self): + nonlocal called + called = True - with raises(NullPointerError): - print(~to_ptr(NULL)) + # Sanity check + Tracked() + assert called is True - ptr2: Pointer[int] = to_ptr(NULL) - ptr2 >>= 1 + called = False + to_ptr(Tracked()) + assert called is True - ptr2 >>= NULL +def test_immortal_objects(): + called = False -@test("operator magic") -def _(): - ptr = m & "test" - assert type(ptr) is Pointer - assert m * ptr == "test" + class Tracked: + def __del__(self): + nonlocal called + called = True + + if sys.version_info < (3, 12): + with pytest.raises(CompatibilityError): + to_ptr(Tracked()).immortalize() + else: + to_ptr(Tracked()).immortalize() + + assert called is False diff --git a/tests/test_var_pointer.py b/tests/test_var_pointer.py deleted file mode 100644 index 0482f74..0000000 --- a/tests/test_var_pointer.py +++ /dev/null @@ -1,54 +0,0 @@ -from ward import raises, test - -from pointers import NULL, NullPointerError, VarPointer, to_var_ptr - -""" -@test("creating variable pointers") -def _(): - var = "hello" - ptr = to_var_ptr(var) - - assert type(ptr) is VarPointer - assert ~ptr == var - - with raises(TypeError): - to_var_ptr("hello") - -@test("variable pointer movement") -def _(): - var = "hello" - var2 = "123456" - ptr = to_var_ptr(var) - ptr2 = to_var_ptr(var2) - - ptr <<= "hi" - print(var, ~ptr) - assert var == "hi" - - ptr <<= ptr2 - assert var == var2 - -@test("variable pointer assignment") -def _(): - var = "hello" - var2 = "123456" - ptr = to_var_ptr(var) - - ptr >>= var2 - assert ~ptr == var2 - ptr >>= NULL - - with raises(NullPointerError): - assert ~ptr - -@test("variable pointer dereferencing") -def _(): - var = "hello" - var2 = "1234" - ptr = to_var_ptr(var) - - assert ~ptr == var - assert ptr.address == id(var) - ptr >>= var2 - assert ~ptr == var2 -"""