Home >Backend Development >Python Tutorial >How Can ctypes Seamlessly Bridge Python and C/C Libraries?

How Can ctypes Seamlessly Bridge Python and C/C Libraries?

DDD
DDDOriginal
2024-12-26 18:37:14384browse

How Can ctypes Seamlessly Bridge Python and C/C   Libraries?

Calling C/C from Python with ctypes

When seeking to establish a bridge between Python and C/C , the ctypes module emerges as a preferred choice. Its seamless integration with Python's standard library ensures stability and widespread accessibility. Unlike swig, which can occasionally encounter issues, ctypes provides a dependable bridge between the two languages.

ctypes excels in its ability to handle compile-time dependencies on Python, allowing your bindings to function flawlessly on any Python installation that supports ctypes, regardless of the version used for compilation.

To illustrate its usage, consider the following C class named Foo:

#include <iostream>

class Foo {
public:
    void bar() {
        std::cout << "Hello" << std::endl;
    }
};

Since ctypes can only interact with C functions, you must declare these functions as extern "C":

extern "C" {
    Foo* Foo_new() { return new Foo(); }
    void Foo_bar(Foo* foo) { foo->bar(); }
}

Compile this code into a shared library:

g++ -c -fPIC foo.cpp -o foo.o
g++ -shared -Wl,-soname,libfoo.so -o libfoo.so  foo.o

Finally, create a Python wrapper to bridge the connection:

from ctypes import cdll
lib = cdll.LoadLibrary('./libfoo.so')

class Foo(object):
    def __init__(self):
        self.obj = lib.Foo_new()

    def bar(self):
        lib.Foo_bar(self.obj)

With this setup, you can effortlessly invoke the C library from Python:

f = Foo()
f.bar()  # Prints "Hello" on the screen

ctypes provides a straightforward and efficient solution for constructing Python bindings to C/C libraries, facilitating seamless interoperability between these programming languages.

The above is the detailed content of How Can ctypes Seamlessly Bridge Python and C/C Libraries?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn