C++ API as an Python Extension Module

Can APIs written in C or C++ always be made into a library, given source code, and consequently be called from Python, due to the intrinsic callable nature of an API?

In other words, given a C/C++ API can you run a setup.py script using distutils on the source and effectively use the C/C++ API from python programs?

Answers


It's a bit more involved than running a setup.py script, but there are tools to wrap C/C++ libraries so you can use them from Python. Some popular ones are:

  • Cython - you write Python-style code, but you can cimport C libraries and call their functions. Cython code is then translated to C and compiled. There's an unsupported tool called cython-codegen to automate writing a simple wrapper.
  • boost.python - For wrapping C++ libraries.
  • SWIG
  • ctypes - Load compiled libraries and call them directly from Python. ctypesgen tries to automatically write a wrapper based on header files.

Certain projects use other tools to generate Python bindings, and they could probably be reused (with varying amounts of effort). PyQt4 uses SIP, PySide (another Qt binding) has shiboken, and GTK et al. have Gobject introspection.


Need Your Help

Android - It takes long to get a GPS-Signal. How to implement a good GPS provider?

android gps location-provider

i wrote an app, that tracks the gps location while jogging. Unfortunately the app needs some time to get a gps signal. When i open other apps like google maps, they are getting immediately the posi...

Rails 4 always adding null value for column

ruby-on-rails postgresql ruby-on-rails-4

I have a column named portfolio_id in portfolio_files table. portfolio_files table belongs_to portfolio table. Now when I create a new record for portfolio_files table, it always create record with...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.