ctypesgen

1.1.1 · active · verified Fri Apr 17

ctypesgen is a Python wrapper generator for `ctypes`, designed to automate the creation of Python bindings for C header files. It parses C/C++ header files and generates Python modules that use the `ctypes` foreign function interface to call functions and access data structures in shared C libraries. The current version is 1.1.1, with releases occurring periodically to address bugs and introduce new features, often yearly or bi-annually.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `ctypesgen` programmatically to generate Python bindings for a simple C header file. It creates a dummy header, invokes `ctypesgen.main.main` with appropriate arguments to create a Python file, and then prints instructions for how to use the generated bindings (which requires compiling the C code into a shared library).

import os
import ctypesgen.main

# 1. Define your C header content
header_content = """
// my_library.h
#ifndef MY_LIBRARY_H
#define MY_LIBRARY_H

int add_numbers(int a, int b);
void print_message(const char* msg);

#endif
"""

# 2. Create a temporary header file
header_file = "my_library.h"
with open(header_file, "w") as f:
    f.write(header_content)

# 3. Define the output Python bindings file
output_file = "my_library_bindings.py"

# 4. Run ctypesgen programmatically using its main function
# Arguments are passed as a list of strings, just like command-line arguments.
ctypesgen.main.main(["-o", output_file, header_file])

print(f"Successfully generated bindings to '{output_file}'")
print("To use them, compile 'my_library.h' into a shared library (e.g., .so, .dylib, .dll),\n"+
      "then import 'my_library_bindings' in Python and load the shared library.")

# 5. Clean up temporary files
os.remove(header_file)

view raw JSON →