Skip to main content
Redhat Developers  Logo
  • Products

    Featured

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat OpenShift AI
      Red Hat OpenShift AI
    • Red Hat Enterprise Linux AI
      Linux icon inside of a brain
    • Image mode for Red Hat Enterprise Linux
      RHEL image mode
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • Red Hat Developer Hub
      Developer Hub
    • View All Red Hat Products
    • Linux

      • Red Hat Enterprise Linux
      • Image mode for Red Hat Enterprise Linux
      • Red Hat Universal Base Images (UBI)
    • Java runtimes & frameworks

      • JBoss Enterprise Application Platform
      • Red Hat build of OpenJDK
    • Kubernetes

      • Red Hat OpenShift
      • Microsoft Azure Red Hat OpenShift
      • Red Hat OpenShift Virtualization
      • Red Hat OpenShift Lightspeed
    • Integration & App Connectivity

      • Red Hat Build of Apache Camel
      • Red Hat Service Interconnect
      • Red Hat Connectivity Link
    • AI/ML

      • Red Hat OpenShift AI
      • Red Hat Enterprise Linux AI
    • Automation

      • Red Hat Ansible Automation Platform
      • Red Hat Ansible Lightspeed
    • Developer tools

      • Red Hat Trusted Software Supply Chain
      • Podman Desktop
      • Red Hat OpenShift Dev Spaces
    • Developer Sandbox

      Developer Sandbox
      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Secure Development & Architectures

      • Security
      • Secure coding
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
      • View All Technologies
    • Start exploring in the Developer Sandbox for free

      sandbox graphic
      Try Red Hat's products and technologies without setup or configuration.
    • Try at no cost
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • Java
      Java icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • API Catalog
    • Product Documentation
    • Legacy Documentation
    • Red Hat Learning

      Learning image
      Boost your technical skills to expert-level with the help of interactive lessons offered by various Red Hat Learning programs.
    • Explore Red Hat Learning
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

How to create Python binding for a Rust library

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

Share:

    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.

    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

    • How to build a Model-as-a-Service platform

    • How Quarkus works with OpenTelemetry on OpenShift

    • Our top 10 articles of 2025 (so far)

    • The benefits of auto-merging GitHub and GitLab repositories

    • Supercharging AI isolation: microVMs with RamaLama & libkrun

    What’s up next?

    Red Hat Insights API

    Find out how to get actionable intelligence using Red Hat Insights 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

    Products

    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform

    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
    © 2025 Red Hat

    Red Hat legal and privacy links

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

    Report a website issue