### Install LLVM using install script Source: https://github.com/trolldbois/ctypeslib/blob/master/README.md Downloads and executes the LLVM installation script to install a specific version of the LLVM toolkit. ```sh wget https://apt.llvm.org/llvm.sh && chmod +x llvm.sh ./llvm.sh 19 ``` ```sh ./llvm.sh 17 ``` -------------------------------- ### Install ctypeslib2 and clang Python package Source: https://github.com/trolldbois/ctypeslib/blob/master/README.md Installs the ctypeslib2 package and the clang Python package, ensuring the clang version matches the installed LLVM clang library. ```sh pip install ctypeslib2 ``` ```sh pip install ctypeslib2 clang==16 ``` ```sh pip install ctypeslib2 clang==14 ``` ```sh pip install ctypeslib2 clang==11 ``` -------------------------------- ### Install libclang on Debian/Ubuntu Source: https://github.com/trolldbois/ctypeslib/blob/master/README.md Installs the libclang development package using apt. Ensure the version number matches your requirements. ```sh sudo apt install libclang1-19 ``` -------------------------------- ### Install Xcode Command Line Tools on macOS Source: https://github.com/trolldbois/ctypeslib/blob/master/README.md Installs the Xcode Command Line Tools, which provides clang and essential headers required for development on macOS. ```sh xcode-select --install ``` -------------------------------- ### Install ctypeslib2 and clang on macOS Source: https://github.com/trolldbois/ctypeslib/blob/master/README.md Installs ctypeslib2 and the corresponding Python bindings for clang on macOS, specifying a version range for the clang package. ```sh % pip install ctypeslib2 'clang>=15,<16' ``` -------------------------------- ### Generate Python bindings from C bitfields Source: https://github.com/trolldbois/ctypeslib/blob/master/README.md Example of converting a C struct with bitfields into a ctypes structure using the clang2py command-line tool. ```c // t.c struct my_bitfield { long a:3; long b:4; unsigned long long c:3; unsigned long long d:3; long f:2; }; ``` ```bash clang2py t.c ``` ```python # -*- coding: utf-8 -*- # # TARGET arch is: [] # WORD_SIZE is: 8 # POINTER_SIZE is: 8 # LONGDOUBLE_SIZE is: 16 # import ctypes class struct_my_bitfield(ctypes.Structure): _pack_ = True # source:False _fields_ = [ ('a', ctypes.c_int64, 3), ('b', ctypes.c_int64, 4), ('c', ctypes.c_int64, 3), ('d', ctypes.c_int64, 3), ('f', ctypes.c_int64, 2), ('PADDING_0', ctypes.c_int64, 49)] __all__ = \ ['struct_my_bitfield'] ``` -------------------------------- ### Generated Python ctypes Code Source: https://github.com/trolldbois/ctypeslib/blob/master/docs/ctypeslib_2.0_Introduction.ipynb Example of Python code generated by ctypeslib for C variables. ```python # -*- coding: utf-8 -*- # # TARGET arch is: [] # WORD_SIZE is: 8 # POINTER_SIZE is: 8 # LONGDOUBLE_SIZE is: 16 # import ctypes version = 2 # Variable ctypes.c_int32 text = 'Hello World!' # Variable ctypes.c_char * 12 minors = [2, 0, 0] # Variable ctypes.c_int32 * 3 __all__ = ['text', 'version', 'minors'] ``` -------------------------------- ### Check clang version on macOS Source: https://github.com/trolldbois/ctypeslib/blob/master/README.md Checks the installed version of clang using xcrun. This is important for ensuring compatibility with Python clang packages. ```sh % xcrun clang --version ``` -------------------------------- ### Generated Python Code for C Structs Source: https://github.com/trolldbois/ctypeslib/blob/master/docs/ctypeslib_2.0_Introduction.ipynb Example of Python code generated by ctypeslib for C structs. This snippet is truncated in the source. ```python # -*- coding: utf-8 -*- # # TARGET arch is: [] # WORD_SIZE is: 8 # POINTER_SIZE is: 8 # LONGDOUBLE_SIZE is: 16 # import ctypes ``` -------------------------------- ### Get parsed items from Clang_Parser Source: https://context7.com/trolldbois/ctypeslib/llms.txt Retrieve the parsed C AST items (typedesc objects) using `get_result()`. These items can then be iterated over. ```python items = parser.get_result() for item in items: print(f"Found: {item.__class__.__name__} - {item.name}") ``` -------------------------------- ### Initialize Clang_Parser with flags Source: https://context7.com/trolldbois/ctypeslib/llms.txt Instantiate `Clang_Parser` with a list of clang flags, such as include paths and C standards. ```python parser = clangparser.Clang_Parser(flags=['-I/usr/include', '-std=c99']) ``` -------------------------------- ### Create win_lean.py Module Source: https://github.com/trolldbois/ctypeslib/blob/master/docs/codegen.txt Generates a Python module 'win_lean.py' with wrappers for the 'lean' Windows API using h2xml.py and xml2py.py. ```bash C:\>python h2xml.py windows.h -D WIN32_LEAN_AND_MEAN -D NO_STRICT -o win_lean.xml -q C:\>python xml2py.py win_lean.xml -w -o win_lean.py ``` -------------------------------- ### Create and Link Structures in Python Source: https://context7.com/trolldbois/ctypeslib/llms.txt Demonstrates creating and linking C-style structures in Python using ctypeslib. Ensure the necessary structures are defined in your Python module. ```python node1 = py_module.struct_LinkedNode() node2 = py_module.struct_LinkedNode() node1.value = 100 node2.value = 200 node1.next = ctypes.pointer(node2) print(f"Node1 value: {node1.value}") print(f"Node1->next->value: {node1.next.contents.value}") ``` -------------------------------- ### Include source locations and comments Source: https://context7.com/trolldbois/ctypeslib/llms.txt Use flags `-e`, `-c`, and `-d` to include source locations, comments, and docstrings in the generated output. ```bash clang2py -e -c -d myheader.h # -e=locations, -c=comments, -d=docstrings ``` -------------------------------- ### Create SDL.py Module on Windows Source: https://github.com/trolldbois/ctypeslib/blob/master/docs/codegen.txt Generates a Python module 'SDL.py' for the SDL library on Windows. Requires defining SDLCALL to an empty value to work around GCC-XML issues. ```bash C:\>python h2xml.py SDL.h -I SDL\include -D SDLCALL= -o SDL.xml -q C:\>python xml2py.py SDL.xml -o SDL.py -l SDL.dll ``` -------------------------------- ### Check version information Source: https://context7.com/trolldbois/ctypeslib/llms.txt Display the version information for ctypeslib and its dependencies using the `--version` flag. ```bash clang2py --version ``` -------------------------------- ### Load shared library and extract symbols Source: https://context7.com/trolldbois/ctypeslib/llms.txt Instantiate the `Library` class with the path to a shared library and the `nm` tool to extract symbol information. ```python lib = Library('/usr/lib/libm.so.6', nm='nm') ``` -------------------------------- ### Create SDL.py Module on Linux Source: https://github.com/trolldbois/ctypeslib/blob/master/docs/codegen.txt Generates a Python module 'SDL.py' for the SDL library on Linux, specifying the correct include path and shared library name. ```bash thomas@linux:~/ctypes/wrap> python h2xml.py SDL/SDL.h -o SDL.xml -q thomas@linux:~/ctypes/wrap> python xml2py.py SDL.xml -o SDL.py -l libSDL.so ``` -------------------------------- ### Create and use structure instances Source: https://context7.com/trolldbois/ctypeslib/llms.txt Instantiate the generated Python structure classes and access their members directly. Use `ctypes.sizeof()` to check the size of the structure. ```python packet = py_module.struct_Packet() packet.header = 0xDEADBEEF packet.length = 128 packet.data[0] = 0x01 packet.data[1] = 0x02 packet.checksum = 0x12345678 print(f"Packet size: {ctypes.sizeof(packet)} bytes") print(f"Header: 0x{packet.header:08X}") ``` -------------------------------- ### Include all declarations from headers Source: https://context7.com/trolldbois/ctypeslib/llms.txt Use `clang2py -i` to include declarations from all specified header files. ```bash clang2py -i myheader.h -o bindings.py ``` -------------------------------- ### Verbose output with statistics Source: https://context7.com/trolldbois/ctypeslib/llms.txt Enable verbose output, including statistics, by using the `--verbose` flag. ```bash clang2py --verbose myheader.h ``` -------------------------------- ### Access C Variables in Python Source: https://github.com/trolldbois/ctypeslib/blob/master/docs/ctypeslib_2.0_Introduction.ipynb Demonstrates accessing the C variables (now Python variables) generated by ctypeslib. ```python print text print 'Brought to you by ctypeslib version', version print minors ``` -------------------------------- ### Parse C header files with h2xml.py Source: https://github.com/trolldbois/ctypeslib/blob/master/docs/codegen.txt Use h2xml.py to generate an XML representation of C header files, including preprocessor definitions. ```bash C:\>python h2xml.py windows.h -o windows.xml -q -c C:\> ``` -------------------------------- ### Handle memory alignment and padding Source: https://github.com/trolldbois/ctypeslib/blob/master/README.md The tool automatically inserts padding fields to match C compiler memory alignment requirements. ```bash clang2py test/data/test-record.c ``` ```python # ... class struct_Node2(Structure): _pack_ = True # source:False _fields_ = [ ('m1', ctypes.c_ubyte), ('PADDING_0', ctypes.c_ubyte * 7), ('m2', POINTER_T(struct_Node)),] # ... ``` -------------------------------- ### Generate Python bindings with custom clang arguments Source: https://github.com/trolldbois/ctypeslib/blob/master/README.md Use the --clang-args flag to provide include paths or other compiler flags during translation. ```c // test-stdbool.c #include typedef struct s_foo { bool bar1; bool bar2; bool bar3; } foo; ``` ```bash clang2py --clang-args="-I/usr/include/clang/4.0/include" test-stdbool.c ``` ```python # -*- coding: utf-8 -*- # # TARGET arch is: ['-I/usr/include/clang/4.0/include'] # WORD_SIZE is: 8 # POINTER_SIZE is: 8 # LONGDOUBLE_SIZE is: 16 # import ctypes class struct_s_foo(ctypes.Structure): _pack_ = True # source:False _fields_ = [ ('bar1', ctypes.c_bool), ('bar2', ctypes.c_bool), ('bar3', ctypes.c_bool),] foo = struct_s_foo __all__ = ['struct_s_foo', 'foo'] ``` -------------------------------- ### Display C header file content Source: https://github.com/trolldbois/ctypeslib/blob/master/docs/ctypeslib_2.0_Introduction.ipynb Uses shell command to display the contents of a test C header file. ```bash !cat test/data/test-stdbool.c ``` -------------------------------- ### Generate constants from preprocessor definitions Source: https://github.com/trolldbois/ctypeslib/blob/master/docs/codegen.txt Extract #define symbols matching a regex pattern from the XML file. ```bash c:\>python xml2py.py windows.xml -r MB_.* # generated by 'xml2py.py' # flags 'windows.xml -r MB_.*' MB_USERICON = 128 MB_DEFBUTTON3 = 512 MB_USEGLYPHCHARS = 4 MB_ABORTRETRYIGNORE = 2 MB_ICONASTERISK = 64 MB_ICONINFORMATION = MB_ICONASTERISK MB_ICONHAND = 16 MB_ICONERROR = MB_ICONHAND MB_ICONEXCLAMATION = 48 MB_ICONWARNING = MB_ICONEXCLAMATION MB_RIGHT = 524288 MB_SYSTEMMODAL = 4096 MB_ICONQUESTION = 32 MB_APPLMODAL = 0 MB_OK = 0 MB_TYPEMASK = 15 MB_MODEMASK = 12288 MB_TASKMODAL = 8192 MB_OKCANCEL = 1 MB_RETRYCANCEL = 5 MB_DEFAULT_DESKTOP_ONLY = 131072 MB_RTLREADING = 1048576 ``` -------------------------------- ### Read Binary Data into Structures Source: https://context7.com/trolldbois/ctypeslib/llms.txt Shows how to parse binary data directly into a Python structure using `from_buffer_copy`. This is useful for interpreting raw byte streams according to a defined C structure. ```python binary_data = bytes([0xEF, 0xBE, 0xAD, 0xDE, 0x80, 0x00] + [0]*256 + [0x78, 0x56, 0x34, 0x12]) packet_from_bytes = py_module.struct_Packet.from_buffer_copy(binary_data) print(f"Parsed header: 0x{packet_from_bytes.header:08X}") ``` -------------------------------- ### Activate comment parsing for documentation Source: https://context7.com/trolldbois/ctypeslib/llms.txt Enable parsing of C comments for documentation generation by calling `activate_comment_parsing()`. ```python parser.activate_comment_parsing() ``` -------------------------------- ### Generate ICreateErrorInfo COM Interface Wrapper Source: https://github.com/trolldbois/ctypeslib/blob/master/docs/codegen.txt Generates a Python wrapper for the ICreateErrorInfo COM interface using xml2py with the -m flag. The _iid_ member requires manual completion. ```bash C:\sf\ctypes\ctypes\wrap> xml2py windows.xml -s ICreateErrorInfo -m ctypes.com ``` ```python # generated by 'xml2py' # flags 'windows.xml -s ICreateErrorInfo -m ctypes.com' from ctypes import * from ctypes.com import IUnknown from ctypes.com import GUID class ICreateErrorInfo(IUnknown): _iid_ = GUID('{}') # please look up iid and fill in! # C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 5366 pass from ctypes.com import HRESULT from ctypes.com import GUID WCHAR = c_wchar OLECHAR = WCHAR LPOLESTR = POINTER(OLECHAR) from ctypes.com import DWORD from ctypes.com import STDMETHOD ICreateErrorInfo._methods_ = IUnknown._methods + [ # C:/Programme/gccxml/bin/Vc71/PlatformSDK/oaidl.h 5366 STDMETHOD(HRESULT, 'SetGUID', [POINTER(GUID)]), STDMETHOD(HRESULT, 'SetSource', [LPOLESTR]), STDMETHOD(HRESULT, 'SetDescription', [LPOLESTR]), STDMETHOD(HRESULT, 'SetHelpFile', [LPOLESTR]), STDMETHOD(HRESULT, 'SetHelpContext', [DWORD]), ] ``` -------------------------------- ### Manipulate C structures in Python Source: https://github.com/trolldbois/ctypeslib/blob/master/docs/ctypeslib_2.0_Introduction.ipynb Demonstrates pointer assignment and field access for structures loaded into the namespace. ```python n1 = namespace.struct_Node() n2 = namespace.struct_Node2() n3 = namespace.struct_Node3() ptr_n2 = ctypes.pointer(n2) n1.val1 = 42 n1.ptr4 = ptr_n2 n2.m1 = 43 n2.m2 = ctypes.pointer(n1) n3.ptr1 = n2.m2 print "node3", n3 print "node3.ptr1", n3.ptr1 print "node3->ptr1.val1",n3.ptr1.contents.val1 print "node3->ptr1.ptr4->m1",n3.ptr1.contents.ptr4.contents.m1 print "node2.m1",n3.ptr1.contents.ptr4.contents.m1 ``` -------------------------------- ### Activate macro parsing Source: https://context7.com/trolldbois/ctypeslib/llms.txt Enable parsing of C macros by calling `activate_macros_parsing()` on the `Clang_Parser` instance. ```python parser.activate_macros_parsing() ``` -------------------------------- ### Cross-architecture compilation Source: https://context7.com/trolldbois/ctypeslib/llms.txt Specify the target architecture for compilation using the `--target` flag. ```bash clang2py --target arm-gnu-linux myheader.h ``` ```bash clang2py --target i386-linux myheader.h ``` ```bash clang2py --target x86_64-Linux myheader.h ``` -------------------------------- ### Execute generated Python code Source: https://context7.com/trolldbois/ctypeslib/llms.txt Use `exec()` to run the generated Python code, making the ctypes-compatible classes available in a namespace. ```python namespace = {} exec(generated_code, namespace) print(namespace['struct_Config']) # ``` -------------------------------- ### Configure C code generation with CodegenConfig Source: https://context7.com/trolldbois/ctypeslib/llms.txt Customize the code generation process using `CodegenConfig` for options like clang flags, symbol filtering, and output formatting. This allows for fine-grained control over the generated bindings. ```python from ctypeslib.codegen import config import ctypeslib import re # Create configuration cfg = config.CodegenConfig() # Add clang preprocessor options cfg.clang_opts.extend([ '-I/usr/include', '-I/usr/local/include', '-DVERSION=2', '-std=c99' ]) # Filter by specific symbols cfg.symbols = ['my_function', 'my_struct', 'MY_CONSTANT'] # Filter by regular expressions cfg.expressions = [re.compile(r'API_.*'), re.compile(r'struct_config.*')] # Control output verbosity cfg.verbose = True cfg.generate_comments = True # Include doxygen-style comments cfg.generate_docstrings = True # Include C prototype in docstrings cfg.generate_locations = True # Include source file locations # Filter declarations to source files only (exclude system headers) cfg.filter_location = True # Select specific type kinds to generate # Options: 'a'=Alias, 'c'=Class/Struct, 'd'=Variable, 'e'=Enum, # 'f'=Function, 'm'=Macro, 's'=Structure, 't'=Typedef, 'u'=Union cfg._init_types("cstu") # Only structs, typedefs, and unions # Cross-compilation target cfg.clang_opts.extend(['-target', 'x86_64-Linux']) # Use the configuration py_module = ctypeslib.translate_files('myheader.h', cfg=cfg) ``` -------------------------------- ### Generate ctypes bindings using clang2py CLI Source: https://context7.com/trolldbois/ctypeslib/llms.txt The `clang2py` command-line tool converts C header files to Python ctypes code. Use it for quick conversions or to generate binding files. ```bash # Basic usage - output to stdout clang2py myheader.h # Output to a file clang2py myheader.h -o bindings.py ``` -------------------------------- ### Load generated code into a Python namespace Source: https://github.com/trolldbois/ctypeslib/blob/master/docs/ctypeslib_2.0_Introduction.ipynb Loads the output of a code generation process into a dictionary-like namespace and inspects structure sizes. ```python namespace = {} exec output.getvalue() in namespace namespace = ctypeslib.codegen.util.ADict(namespace) import ctypes print "sizeof(struct Name) ==", ctypes.sizeof(namespace.struct_Name) print "sizeof(struct Name2) ==", ctypes.sizeof(namespace.struct_Name2) ``` -------------------------------- ### CLI Usage: clang2py Source: https://github.com/trolldbois/ctypeslib/blob/master/README.md The clang2py command-line tool parses C header files and generates Python bindings. It accepts multiple source files and provides extensive options to customize the generated code. ```APIDOC ## CLI Command: clang2py ### Description Generates Python code from C header files using libclang. ### Usage clang2py [options] files [files ...] ### Parameters #### Positional Arguments - **files** (list) - Required - Source filenames to process. #### Options - **-c, --comments** (flag) - Optional - Include source doxygen-style comments. - **-d, --doc** (flag) - Optional - Include docstrings containing C prototype and source file location. - **-k, --kind** (string) - Optional - Kind of type descriptions to include (a=Alias, c=Class, d=Variable, e=Enumeration, f=Function, m=Macro, s=Structure, t=Typedef, u=Union). - **-o, --output** (string) - Optional - Output filename (defaults to standard output). - **-t, --target** (string) - Optional - Target architecture (default: x86_64-Linux). - **--clang-args** (string) - Optional - Clang options, in quotes (e.g., "-std=c99 -Wall"). - **-v, --verbose** (flag) - Optional - Enable verbose output. - **-V, --version** (flag) - Optional - Show program version and exit. ``` -------------------------------- ### Print Generated Python Code Source: https://github.com/trolldbois/ctypeslib/blob/master/docs/ctypeslib_2.0_Introduction.ipynb Print the generated Python code from the StringIO output stream. ```python print output.getvalue() ``` -------------------------------- ### Generate RegisterClassA Wrapper with ctypeslib Source: https://github.com/trolldbois/ctypeslib/blob/master/docs/codegen.txt Generates a Python wrapper for the RegisterClassA function using xml2py. Ensure Python 2.3 compatibility by omitting the -d flag. ```bash C:\>python xml2py.py windows.xml -w -s RegisterClass -d ``` ```python # generated by 'xml2py' # flags 'windows.xml -w -s RegisterClass' from ctypes import * from ctypes import decorators WORD = c_ushort ATOM = WORD class tagWNDCLASSA(Structure): pass WNDCLASSA = tagWNDCLASSA @ decorators.stdcall(ATOM, 'user32', [POINTER(WNDCLASSA)]) def RegisterClassA(p1): return RegisterClassA._api_(p1) RegisterClass = RegisterClassA UINT = c_uint LONG_PTR = c_long LRESULT = LONG_PTR WNDPROC = WINFUNCTYPE(LRESULT, c_void_p, c_uint, c_uint, c_long) PVOID = c_void_p HANDLE = PVOID HINSTANCE = HANDLE HICON = HANDLE HCURSOR = HICON HBRUSH = HANDLE CHAR = c_char LPCSTR = POINTER(CHAR) tagWNDCLASSA._fields_ = [ ('style', UINT), ('lpfnWndProc', WNDPROC), ('cbClsExtra', c_int), ('cbWndExtra', c_int), ('hInstance', HINSTANCE), ('hIcon', HICON), ('hCursor', HCURSOR), ('hbrBackground', HBRUSH), ('lpszMenuName', LPCSTR), ('lpszClassName', LPCSTR), ] assert sizeof(tagWNDCLASSA) == 40, sizeof(tagWNDCLASSA) assert alignment(tagWNDCLASSA) == 4, alignment(tagWNDCLASSA) ``` -------------------------------- ### Generate Python structure definitions with xml2py.py Source: https://github.com/trolldbois/ctypeslib/blob/master/docs/codegen.txt Extract specific C structures from the generated XML file into Python ctypes code. ```bash C:\>xml2py.py windows.xml -s RECT from ctypes import * LONG = c_long class tagRECT(Structure): pass RECT = tagRECT tagRECT._fields_ = [ ('left', c_long), ('top', c_long), ('right', c_long), ('bottom', c_long), ] assert sizeof(tagRECT) == 16, sizeof(tagRECT) assert alignment(tagRECT) == 4, alignment(tagRECT) C:\> ``` -------------------------------- ### Pass additional clang arguments Source: https://context7.com/trolldbois/ctypeslib/llms.txt Provide extra arguments to the clang compiler using `--clang-args`. ```bash clang2py --clang-args="-I/usr/local/include -DDEBUG=1 -std=c99" myheader.h ``` -------------------------------- ### Link with a shared library Source: https://context7.com/trolldbois/ctypeslib/llms.txt Use the `-l` flag to link with a shared library, which helps resolve exported functions. ```bash clang2py -l /path/to/libmylib.so myheader.h ``` -------------------------------- ### Define C Headers Source: https://github.com/trolldbois/ctypeslib/blob/master/docs/ctypeslib_2.0_Introduction.ipynb Define C headers as a multi-line string for parsing. ```python c_headers = ''' /** very simple tests */ int version = 2; char text[] = "Hello World!"; int minors[] = {2,0,0}; ''' ``` -------------------------------- ### Work with bitfields in structures Source: https://context7.com/trolldbois/ctypeslib/llms.txt Instantiate structure classes containing bitfields and assign values to the bitfield members. The size of the structure can be verified using `ctypes.sizeof()`. ```python flags = py_module.struct_BitFlags() flags.flag_a = 1 flags.flag_b = 5 flags.flag_c = 15 print(f"BitFlags size: {ctypes.sizeof(flags)} bytes") ``` -------------------------------- ### Emulate ctypes pointers Source: https://github.com/trolldbois/ctypeslib/blob/master/docs/ctypeslib_2.0_Introduction.ipynb Provides a mechanism to emulate pointer types when the local word size differs from the target architecture. ```python # if local wordsize is same as target, keep ctypes pointer function. if ctypes.sizeof(ctypes.c_void_p) == 8: POINTER_T = ctypes.POINTER else: # required to access _ctypes import _ctypes # Emulate a pointer class using the approriate c_int32/c_int64 type # The new class should have : # ['__module__', 'from_param', '_type_', '__dict__', '__weakref__', '__doc__'] # but the class should be submitted to a unique instance for each base type # to that if A == B, POINTER_T(A) == POINTER_T(B) ctypes._pointer_t_type_cache = {} def POINTER_T(pointee): # a pointer should have the same length as LONG fake_ptr_base_type = ctypes.c_uint64 # specific case for c_void_p if pointee is None: # VOID pointer type. c_void_p. pointee = type(None) # ctypes.c_void_p # ctypes.c_ulong clsname = 'c_void' else: clsname = pointee.__name__ if clsname in ctypes._pointer_t_type_cache: return ctypes._pointer_t_type_cache[clsname] # make template class _T(_ctypes._SimpleCData,): _type_ = 'L' _subtype_ = pointee def _sub_addr_(self): return self.value def __repr__(self): return '%s(%d)'%(clsname, self.value) def contents(self): raise TypeError('This is not a ctypes pointer.') def __init__(self, **args): raise TypeError('This is not a ctypes pointer. It is not instanciable.') _class = type('LP_%d_%s'%(8, clsname), (_T,),{}) ctypes._pointer_t_type_cache[clsname] = _class return _class ``` -------------------------------- ### Translate C code programmatically Source: https://github.com/trolldbois/ctypeslib/blob/master/README.md Use the ctypeslib.translate and translate_files functions to convert C source strings or files into Python modules. ```python import ctypeslib py_module = ctypeslib.translate('''int i = 12;''') print(py_module.i) # Prints 12 py_module2 = ctypeslib.translate('''struct coordinates { int i ; int y; };''') print(py_module2.struct_coordinates) # print(py_module2.struct_coordinates(1,2)) # # input files, output file py_module3 = ctypeslib.translate_files(['mytest.c'], outfile=open('mytest.py', 'w')) print(open('mytest.py').read()) # input files, output code py_module4 = ctypeslib.translate_files(['mytest.c']) print(open('mytest.py').read()) # input files, output code, with clang options, like cross-platform from ctypeslib.codegen import config cfg = config.CodegenConfig() cfg.clang_opts.extend(['-target', 'arm-gnu-linux']) py_module5 = ctypeslib.translate_files(['mytest.c'], cfg=cfg) print(open('mytest.py').read()) ``` -------------------------------- ### Read C code from stdin Source: https://context7.com/trolldbois/ctypeslib/llms.txt Pipe C code directly to `clang2py` using stdin by specifying a hyphen `-` as the input file. ```bash echo "int x = 42;" | clang2py - ``` -------------------------------- ### Parse C Headers with ClangParser Source: https://github.com/trolldbois/ctypeslib/blob/master/docs/ctypeslib_2.0_Introduction.ipynb Use Clang_Parser to parse C header strings into intermediate Python objects. Requires LLVM Clang library and its Python bindings. ```python import ctypeslib from ctypeslib.codegen import clangparser # let's create a parser parser = clangparser.Clang_Parser(flags=[]) # parse the c headers parser.parse_string(c_headers) # get the result items = parser.get_result() print items ``` -------------------------------- ### Translate C files to Python namespace Source: https://context7.com/trolldbois/ctypeslib/llms.txt The `translate_files` function processes C header files to generate Python ctypes bindings. It can output to a file or return a Python namespace. ```python import ctypeslib from ctypeslib.codegen import config import tempfile # Basic usage: translate a C file and get Python namespace py_module = ctypeslib.translate_files('myheader.h') # Translate multiple files py_module = ctypeslib.translate_files(['header1.h', 'header2.h', 'types.h']) # Write output to a Python file with open('generated_bindings.py', 'w') as outfile: ctypeslib.translate_files(['mylib.h'], outfile=outfile) # Advanced usage with configuration cfg = config.CodegenConfig() cfg.clang_opts.extend(['-I/usr/local/include', '-DDEBUG=1']) py_module = ctypeslib.translate_files('mylib.h', cfg=cfg) # Cross-architecture generation (e.g., for ARM target) cfg = config.CodegenConfig() cfg.clang_opts.extend(['-target', 'arm-gnu-linux']) with tempfile.NamedTemporaryFile(suffix='.py', mode='w+') as tmpfile: ctypeslib.translate_files('embedded_types.h', outfile=tmpfile, cfg=cfg) tmpfile.seek(0) generated_code = tmpfile.read() print(generated_code) # Shows ARM-specific sizes (WORD_SIZE: 4) ``` -------------------------------- ### Translate C structures to Python classes Source: https://context7.com/trolldbois/ctypeslib/llms.txt Use `ctypeslib.translate()` to convert C structure definitions into ctypes-compatible Python classes. ```python py_module = ctypeslib.translate(''' struct Packet { unsigned int header; unsigned short length; unsigned char data[256]; unsigned int checksum; }; struct LinkedNode { int value; struct LinkedNode *next; }; struct BitFlags { unsigned int flag_a : 1; unsigned int flag_b : 3; unsigned int flag_c : 4; unsigned int reserved : 24; }; ''') ``` -------------------------------- ### Define custom types and structures Source: https://github.com/trolldbois/ctypeslib/blob/master/docs/ctypeslib_2.0_Introduction.ipynb Defines 128-bit integer types, long double types, and various ctypes.Structure definitions with manual padding. ```python c_int128 = ctypes.c_ubyte*16 c_uint128 = c_int128 void = None if ctypes.sizeof(ctypes.c_longdouble) == 16: c_long_double_t = ctypes.c_longdouble else: c_long_double_t = ctypes.c_ubyte*16 class struct_Name(ctypes.Structure): _pack_ = True # source:False _fields_ = [ ('member1', ctypes.c_int16), ('member2', ctypes.c_int32), ('member3', ctypes.c_uint32), ('member4', ctypes.c_uint32), ('member5', ctypes.c_uint32), ] class struct_Name2(ctypes.Structure): _pack_ = True # source:False _fields_ = [ ('member1', ctypes.c_int16), ('PADDING_0', ctypes.c_ubyte * 2), ('member2', ctypes.c_int32), ('member3', ctypes.c_uint32), ('member4', ctypes.c_uint32), ('member5', ctypes.c_uint32), ] class struct_Node(ctypes.Structure): pass class struct_Node2(ctypes.Structure): _pack_ = True # source:False _fields_ = [ ('m1', ctypes.c_ubyte), ('PADDING_0', ctypes.c_ubyte * 7), ('m2', POINTER_T(struct_Node)), ] struct_Node._pack_ = True # source:False struct_Node._fields_ = [ ('val1', ctypes.c_uint32), ('PADDING_0', ctypes.c_ubyte * 4), ('ptr2', POINTER_T(None)), ('ptr3', POINTER_T(ctypes.c_int32)), ('ptr4', POINTER_T(struct_Node2)), ] class struct_Node3(ctypes.Structure): _pack_ = True # source:False _fields_ = [ ('ptr1', POINTER_T(struct_Node)), ('ptr2', POINTER_T(ctypes.c_ubyte)), ('ptr3', POINTER_T(ctypes.c_uint16)), ('ptr4', POINTER_T(ctypes.c_uint32)), ('ptr5', POINTER_T(ctypes.c_uint64)), ('ptr6', POINTER_T(ctypes.c_uint64)), ('ptr7', POINTER_T(ctypes.c_double)), ('ptr8', POINTER_T(c_long_double_t)), ('ptr9', POINTER_T(None)), ] __all__ = ['struct_Name', 'struct_Node', 'struct_Node3', 'struct_Node2', 'struct_Name2'] ``` -------------------------------- ### Configure CodegenConfig for library searching Source: https://context7.com/trolldbois/ctypeslib/llms.txt Set the `searched_dlls` attribute in `CodegenConfig` to a list of `Library` objects to specify which libraries should be searched for exported functions during code generation. ```python cfg = config.CodegenConfig() # Specify libraries to search for exported functions cfg.searched_dlls = [Library('/path/to/libmylib.so', nm='nm')] ``` -------------------------------- ### Select specific type kinds Source: https://context7.com/trolldbois/ctypeslib/llms.txt Use `clang2py -k` to select specific C type kinds for parsing. Default includes classes, variables, enums, functions, structs, typedefs, and unions. ```bash clang2py -k cdefstu myheader.h # Default: classes, variables, enums, functions, structs, typedefs, unions ``` ```bash clang2py -k e myheader.h # Only enumerations ``` ```bash clang2py -k m myheader.h # Only macros ``` -------------------------------- ### Generate Python code from parsed items Source: https://context7.com/trolldbois/ctypeslib/llms.txt Use the `Generator` class to create Python code from the parsed C items. The output is typically written to a `StringIO` object. ```python output = StringIO() cfg = config.CodegenConfig() generator = codegenerator.Generator(output, cfg=cfg) generator.generate(parser, items) generated_code = output.getvalue() ``` -------------------------------- ### Translate C code string to Python namespace Source: https://context7.com/trolldbois/ctypeslib/llms.txt Use the `translate` function for direct conversion of C code strings into a Python namespace. This is useful for small C snippets or when C code is available as a string. ```python import ctypeslib # Translate C code string to Python namespace py_module = ctypeslib.translate('' int version = 42; char message[] = "Hello from C!"; struct Point { int x; int y; }; struct Rectangle { struct Point top_left; struct Point bottom_right; unsigned int color; }; enum Status { OK = 0, ERROR = 1, PENDING = 2 }; '') # Access translated variables print(py_module.version) # Output: 42 print(py_module.message) # Output: 'Hello from C!' # Use translated structures point = py_module.struct_Point(x=10, y=20) print(f"Point: ({point.x}, {point.y})") # Output: Point: (10, 20) rect = py_module.struct_Rectangle() rect.top_left.x = 0 rect.top_left.y = 0 rect.bottom_right.x = 100 rect.bottom_right.y = 50 rect.color = 0xFF0000 print(f"Rectangle width: {rect.bottom_right.x - rect.top_left.x}") # Output: 100 # Access enum values print(py_module.OK) # Output: 0 print(py_module.ERROR) # Output: 1 print(py_module.PENDING) # Output: 2 ``` -------------------------------- ### Set CLANG_LIBRARY_PATH environmental variable Source: https://github.com/trolldbois/ctypeslib/blob/master/README.md Sets the CLANG_LIBRARY_PATH environment variable to specify the location of the libclang library file. This is useful for resolving version compatibility issues. ```sh export CLANG_LIBRARY_PATH=/lib/x86_64-linux-gnu/libclang-11.so.1 clang2py --version ``` -------------------------------- ### Skip macOS SDK detection Source: https://github.com/trolldbois/ctypeslib/blob/master/README.md Disables the automatic detection of the macOS SDK by ctypeslib2. This requires manual specification of clang arguments. ```sh export CTYPESLIB2_SKIP_MACOS_SDK=1 ``` -------------------------------- ### Parse and Generate Code for C Structs Source: https://github.com/trolldbois/ctypeslib/blob/master/docs/ctypeslib_2.0_Introduction.ipynb Parse complex C structs using Clang_Parser and generate Python ctypes code using Generator. The output is written to a StringIO object. ```python parser = clangparser.Clang_Parser(flags=[]) parser.parse_string(structs) items = parser.get_result() output = StringIO() gen = codegenerator.Generator(output) gen.generate(parser, items) print output.getvalue() ``` -------------------------------- ### Parse C code from a string Source: https://context7.com/trolldbois/ctypeslib/llms.txt Use `parse_string()` to parse C code directly from a Python string. This method populates the parser's internal AST. ```python c_code = ''' #define MAX_SIZE 1024 #define API_VERSION "2.0" /** Configuration structure for the library */ struct Config { int timeout; char name[64]; unsigned int flags; }; typedef struct Config ConfigType; ''' parser.parse_string(c_code) ``` -------------------------------- ### Access symbol addresses from Library Source: https://context7.com/trolldbois/ctypeslib/llms.txt Access the addresses of exported symbols from a loaded `Library` object. Handle `AttributeError` if a symbol is not found. ```python try: sin_addr = lib.sin cos_addr = lib.cos print(f"sin address: {sin_addr}") print(f"cos address: {cos_addr}") except AttributeError as e: print(f"Symbol not found: {e}") ``` -------------------------------- ### Filter symbols by regular expression Source: https://context7.com/trolldbois/ctypeslib/llms.txt Use `clang2py -r` to filter declarations using regular expressions. ```bash clang2py -r 'API_.*' -r 'config_.*' myheader.h ``` -------------------------------- ### Generate Python ctypes Code Source: https://github.com/trolldbois/ctypeslib/blob/master/docs/ctypeslib_2.0_Introduction.ipynb Use Generator to produce Python source code from parsed C items. The output is written to a StringIO object. ```python # we need a output stream to store the generated code from StringIO import StringIO output = StringIO() from ctypeslib.codegen import codegenerator # get the generator gen = codegenerator.Generator(output) # and produce the code gen.generate(parser, items) ``` -------------------------------- ### Filter symbols by name Source: https://context7.com/trolldbois/ctypeslib/llms.txt Use `clang2py -s` to filter declarations by specific symbol names. ```bash clang2py -s my_function -s my_struct myheader.h ``` -------------------------------- ### Define Complex C Structs Source: https://github.com/trolldbois/ctypeslib/blob/master/docs/ctypeslib_2.0_Introduction.ipynb Define complex C structs with various member types, including nested structs and pointers, for parsing. ```c struct Name { short member1; int member2; unsigned int member3; unsigned int member4; unsigned int member5; } __attribute__((packed)); struct Name2 { short member1; int member2; unsigned int member3; unsigned int member4; unsigned int member5; }; struct Node { unsigned int val1; void * ptr2; int * ptr3; struct Node2 * ptr4; }; struct Node2 { unsigned char m1; struct Node * m2; }; struct Node3 { struct Node * ptr1; unsigned char * ptr2; unsigned short * ptr3; unsigned int * ptr4; unsigned long * ptr5; unsigned long long * ptr6; double * ptr7; long double * ptr8; void * ptr9; }; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.