Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python-C integration: Ctypes, CFFI or create a Binary Module

Basically I want to make a Python program call functions written in C.

So (as far as I know) my options are:

  • CTypes/CFFI
    • Create a DLL/SO/DyLib containing the C functions and access them using CTypes or CFFI. Apparently CFFI is way faster with the only drawback of having to declare in python all the functions signatures.
    • Pros:
      • Don't have to make any adaptation in my C functions. All type-translation is done in Python.
    • Cons:
      • Performance ?
  • Python Binary Module
    • Write a python interface in C, converting my C module into a binary python module
    • Pros:
      • Performance ?
    • Cons:
      • All type-translation is done in C. Using [SIP][3] this might be automated.

Convert the C module into a python binary module is really faster ?

Does both solutions support sending python callbacks to C functions ?

Is SIP a good option to generate a python interface ? Are there any other options ?

Are there any other particularities in any of them ?

like image 594
romulof Avatar asked Jul 19 '13 21:07

romulof


People also ask

What is Cffi module in Python?

CFFI is an external package providing a C Foreign Function Interface for Python. CFFI allows one to interact with almost any C code from Python.


1 Answers

I was just reviewing an old list of options I published related to this: http://stromberg.dnsalias.org/~strombrg/speeding-python/

If you're only targeting CPython (2.x or 3.x), I'd probably go for Cython.

If you want to be able to run on Pypy too, CFFI might be good; I've not tried it yet, but it sounds great. It's not entirely like ctypes though - ctypes is more ABI level, while CFFI is more API level - which is nice.

If you want to be able to run on Jython too, subprocess is probably your best bet.

like image 82
dstromberg Avatar answered Sep 17 '22 13:09

dstromberg