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 :
#includeclass Foo{ public: void bar(){ std::cout 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.oFinally, 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
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3