Home >Backend Development >Python Tutorial >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; } };
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(); } }
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
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)
With this setup, you can now invoke the C functions seamlessly from Python:
f = Foo() f.bar() # Output: "Hello" displayed on screen
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!