Interfacing C/C with Python
Python's ease of use and extensibility make it an attractive language for programmers of all levels. However, there are times when integrating with existing C/C libraries is desirable. This article explores the most efficient method for constructing Python bindings for these libraries.
The ctypes module, a part of Python's standard library, offers a stable and widely available solution for this task. Unlike other binding methods, ctypes doesn’t rely on the Python version against which it was compiled, ensuring compatibility with various Python installations.
Consider the following code snippet written in C :
#include <iostream> class Foo{ public: void bar(){ std::cout << "Hello" << std::endl; } };
To interface this with Python, we must declare the functions as extern "C" for ctypes to recognize them:
extern "C" { Foo* Foo_new(){ return new Foo(); } void Foo_bar(Foo* foo){ foo->bar(); } }
Next, we compile this code into a shared library using:
g++ -c -fPIC foo.cpp -o foo.o g++ -shared -Wl,-soname,libfoo.so -o libfoo.so foo.o
Finally, we create a Python wrapper:
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 wrapper, we can interact with our C library in Python:
f = Foo() f.bar() # Prints "Hello" to standard output
The above is the detailed content of How Can I Efficiently Create Python Bindings for C/C Libraries Using ctypes?. For more information, please follow other related articles on the PHP Chinese website!