Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • Guided learning
      Receive custom learning paths powered by our AI assistant.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

How to create Python binding for a Rust library

September 5, 2022
Gris Ge
Related topics:
C, C#, C++LinuxPythonRust
Related products:
Red Hat Enterprise Linux

    This article continues a series about how to take advantage of the recent Rust support added to Linux. The previous articles in the series are:

    • 3 essentials for writing a Linux system library in Rust (part 1)
    • How to create C binding for a Rust library (part 2)
    • Build trust in continuous integration for your Rust library (part 4)

    This third installment demonstrates how to create Python bindings so that Python projects can use your Rust library.

    You can download the demo code from its GitHub repository. The package contains:

    • An echo server listening on the Unix socket /tmp/librabc
    • A Rust crate that connects to the socket and sends a ping packet every 2 seconds
    • A C/Python binding
    • A command-line interface (CLI) for the client

    Elements of a Python binding

    The PyO3 project can generate a Python-compiled extension. But I personally like to wrap the C library shown in the previous section into a Python module using the ctypes module instead of depending on the big, feature-rich PyO3 project.

    You can check the full code of my binding in the GitHub repository. The basic workflow in the code is:

    1. Use ctypes.cdll.LoadLibrary("librabc.so.0") to load the C library.
    2. Implement __init__() for class RabcClient to start the connection.
    3. Pass output pointers to C functions using ctyps.byref().
    4. Free the memory used by the logs, error messages, etc.
    5. Implement __del__() for the RabcClientclass to drop the connection.

    Unlike pure Python projects, when using the C library, your need to take care of memory management. We will look at memory management for various types.

    Output pointer to a C string

    The following Python code creates a pointer to a string:

    
    foo = ctypes.c_char_p()

    The code is equivalent to the following C code:

    
    char * foo = NULL

    The Python function byref(foo) is equivalent to (char **) & foo in C. In order to store the output pointer to the C string, use bytes.decode() to copy and convert the content to Python string, then free the C memory:

    
    c_reply = c_char_p()
    rc = lib.rabc_client_process(
        # Many lines omitted
        ctypes.byref(c_reply),
    )
    
    if reply:
        reply = c_reply.value.decode("utf-8")
        lib.rabc_cstring_free(c_reply)
        return reply

    Output pointer to a C opaque struct

    An opaque struct in C does not have a struct definition in the public header, so there is no field or size information available for the struct. The following excerpt from the demo code shows how to use such a struct in Python:

    
    # Opaque struct
    class _ClibRabcClient(ctypes.Structure):
        pass
    
    class RabcClient:
        def __init__(self):
            self._c_pointer = ctypes.POINTER(_ClibRabcClient)()
            # Many lines omitted
            rc = lib.rabc_client_new(
                ctypes.byref(self._c_pointer),
                # Many arguments omitted
            )
    
        def __del__(self):
            if self._c_pointer:
                lib.rabc_client_free(self._c_pointer)

    The clause ctypes.POINTER(_ClibRabcClient)() is equivalent to struct rabc_client *client = NULL in C.

    Wrap the variable in ctypes.byref() to use it as an output pointer.

    Output pointer to an integer array

    Unlike an opaque struct, Python knows the memory size of an integer. So once you have the memory address of the first element and the length of an integer array, you can iterate over the array's contents using (c_uint64 * event_count.value).from_address().

    This technique is illustrated in the following example code:

    
    c_events = ctypes.POINTER(c_uint64)()
    event_count = c_uint64(0)
    rc = lib.rabc_client_poll(
        c_uint32(wait_time),
        ctypes.byref(c_events),
        # Many arguments omitted
    )
    
    # Many lines omitted
    
    events = list(
        (c_uint64 * event_count.value).from_address(
            ctypes.addressof(c_events.contents)
        )
    )
    lib.rabc_events_free(c_events, event_count)
    return events

    Bindings allow multiple languages to use a Rust library

    The general procedure in this series is to create a Rust library along with a thread-safe and memory-safe C binding. We then used Python code for a Python binding, invoking the C library. With this workflow, you need to deal only with the memory and structure differences between Rust and C. Fortunately, Rust handles the differences very smoothly. We hope you found this series informative.

    Last updated: November 5, 2025

    Related Posts

    • Build your first application using Python with Red Hat Container Development Kit (CDK)

    • Getting started with rust-toolset

    • Troubleshooting and FAQ: Red Hat Enterprise Linux

    • Find and compare Python libraries with project2vec

    Recent Posts

    • Every layer counts: Defense in depth for AI agents with Red Hat AI

    • Fun in the RUN instruction: Why container builds with distroless images can surprise you

    • Trusted software factory: Building trust in the agentic AI era

    • Build a zero trust AI pipeline with OpenShift and RHEL CVMs

    • Red Hat Hardened Images: Top 5 benefits for software developers

    What’s up next?

    Red Hat Insights API

    Find out how to get actionable intelligence using Red Hat Lightspeed APIs so you can identify and address operational and vulnerability risks in your Red Hat Enterprise Linux environments before an issue results in downtime.

    Get the cheat sheet
    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Build

    • Developer Sandbox
    • Developer tools
    • Interactive tutorials
    • API catalog

    Quicklinks

    • Learning resources
    • E-books
    • Cheat sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site status dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2026 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Chat Support

    Please log in with your Red Hat account to access chat support.