Home > Backend Development > Python Tutorial > How Can Python's ctypes Module Seamlessly Integrate with C/C Libraries?

How Can Python's ctypes Module Seamlessly Integrate with C/C Libraries?

Linda Hamilton
Release: 2024-12-11 12:29:11
Original
660 people have browsed it

How Can Python's ctypes Module Seamlessly Integrate with C/C   Libraries?

Leveraging Python for C/C Integration

Python offers versatile capabilities for interfacing with external libraries. One common scenario is invoking C or C functions from within Python. To achieve this, deploying the ctypes module is an effective approach. In contrast to certain third-party tools, ctypes is embedded in the Python standard library, ensuring increased stability and widespread availability.

Utilizing ctypes enables you to circumvent the compile-time dependency on Python. Consequently, any Python instance equipped with ctypes can leverage your binding, irrespective of the version used during compilation.

To illustrate the usage of ctypes, let's consider a basic C class, Foo, defined in a file named foo.cpp:

#include <iostream>

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

To facilitate interaction with ctypes, we need to declare the C functions as extern "C":

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

Next, we 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
Copy after login

Finally, we write a Python wrapper to bridge the gap:

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)
Copy after login

With this setup, you can now invoke the C functions seamlessly from Python:

f = Foo()
f.bar()  # Output: "Hello" displayed on screen
Copy after login

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template