SlideShare a Scribd company logo
Submit Search
Upload
Login
Signup
Call a C API from Python becomes more enjoyable with CFFI, Jean-Sébastien Bevilacqua
Report
Pôle Systematic Paris-Region
Follow
Pôle Systematic Paris-Region
Jun. 15, 2017
•
0 likes
•
886 views
1
of
45
Call a C API from Python becomes more enjoyable with CFFI, Jean-Sébastien Bevilacqua
Jun. 15, 2017
•
0 likes
•
886 views
Download Now
Download to read offline
Report
Technology
PyParis 2017 http://pyparis.org
Pôle Systematic Paris-Region
Follow
Pôle Systematic Paris-Region
Recommended
Call a C API from Python becomes more enjoyable with CFFI
LINAGORA
1.1K views
•
47 slides
Cython - close to metal Python
Taras Lyapun
2.6K views
•
26 slides
Cling the llvm based interpreter
Roberto Nogueira
699 views
•
31 slides
Cython compiler
Tanikella Sai Abhijyan
109 views
•
6 slides
Mypy pycon-fi-2012
jukkaleh
2K views
•
44 slides
Brief Introduction to Cython
Aleksandar Jelenak
1.3K views
•
26 slides
More Related Content
More from Pôle Systematic Paris-Region
OSIS19_Cloud : Qu’apporte l’observabilité à la gestion de configuration? par ...
Pôle Systematic Paris-Region
349 views
•
38 slides
OSIS19_Cloud : Performance and power management in virtualized data centers, ...
Pôle Systematic Paris-Region
288 views
•
27 slides
OSIS19_Cloud : Des objets dans le cloud, et qui y restent -- L'expérience du ...
Pôle Systematic Paris-Region
271 views
•
30 slides
OSIS19_Cloud : Attribution automatique de ressources pour micro-services, Alt...
Pôle Systematic Paris-Region
229 views
•
9 slides
OSIS19_IoT : State of the art in security for embedded systems and IoT, by Pi...
Pôle Systematic Paris-Region
348 views
•
19 slides
Osis19_IoT: Proof of Pointer Programs with Ownership in SPARK, by Yannick Moy
Pôle Systematic Paris-Region
204 views
•
19 slides
More from Pôle Systematic Paris-Region
(20)
OSIS19_Cloud : Qu’apporte l’observabilité à la gestion de configuration? par ...
Pôle Systematic Paris-Region
•
349 views
OSIS19_Cloud : Performance and power management in virtualized data centers, ...
Pôle Systematic Paris-Region
•
288 views
OSIS19_Cloud : Des objets dans le cloud, et qui y restent -- L'expérience du ...
Pôle Systematic Paris-Region
•
271 views
OSIS19_Cloud : Attribution automatique de ressources pour micro-services, Alt...
Pôle Systematic Paris-Region
•
229 views
OSIS19_IoT : State of the art in security for embedded systems and IoT, by Pi...
Pôle Systematic Paris-Region
•
348 views
Osis19_IoT: Proof of Pointer Programs with Ownership in SPARK, by Yannick Moy
Pôle Systematic Paris-Region
•
204 views
Osis18_Cloud : Pas de commun sans communauté ?
Pôle Systematic Paris-Region
•
658 views
Osis18_Cloud : Projet Wolphin
Pôle Systematic Paris-Region
•
231 views
Osis18_Cloud : Virtualisation efficace d’architectures NUMA
Pôle Systematic Paris-Region
•
201 views
Osis18_Cloud : DeepTorrent Stockage distribué perenne basé sur Bittorrent
Pôle Systematic Paris-Region
•
229 views
Osis18_Cloud : Software-heritage
Pôle Systematic Paris-Region
•
132 views
OSIS18_IoT: L'approche machine virtuelle pour les microcontrôleurs, le projet...
Pôle Systematic Paris-Region
•
264 views
OSIS18_IoT: La securite des objets connectes a bas cout avec l'os et riot
Pôle Systematic Paris-Region
•
484 views
OSIS18_IoT : Solution de mise au point pour les systemes embarques, par Julio...
Pôle Systematic Paris-Region
•
168 views
OSIS18_IoT : Securisation du reseau des objets connectes, par Nicolas LE SAUZ...
Pôle Systematic Paris-Region
•
93 views
OSIS18_IoT : Ada and SPARK - Defense in Depth for Safe Micro-controller Progr...
Pôle Systematic Paris-Region
•
248 views
OSIS18_IoT : RTEMS pour l'IoT professionnel, par Pierre Ficheux (Smile ECS)
Pôle Systematic Paris-Region
•
248 views
PyParis 2017 / Un mooc python, by thierry parmentelat
Pôle Systematic Paris-Region
•
2.5K views
PyParis2017 / Python pour les enseignants des classes préparatoires, by Olivi...
Pôle Systematic Paris-Region
•
390 views
PyParis 2017 / Unicode and bytes demystified, by Boris Feld
Pôle Systematic Paris-Region
•
566 views
Recently uploaded
Machine learning with quantum computers
Speck&Tech
95 views
•
20 slides
The Ultimate Administrator’s Guide to HCL Nomad Web
panagenda
65 views
•
71 slides
Demystifying ML/AI
Matthew Reynolds
41 views
•
30 slides
Advancing Equity and Inclusion for Deaf Students in Higher Education
3Play Media
154 views
•
24 slides
Netwitness RT - Don’t scratch that patch.pptx
Stefano Maccaglia
105 views
•
24 slides
Getting your enterprise ready for Microsoft 365 Copilot
Vignesh Ganesan I Microsoft MVP
167 views
•
38 slides
Recently uploaded
(20)
Machine learning with quantum computers
Speck&Tech
•
95 views
The Ultimate Administrator’s Guide to HCL Nomad Web
panagenda
•
65 views
Demystifying ML/AI
Matthew Reynolds
•
41 views
Advancing Equity and Inclusion for Deaf Students in Higher Education
3Play Media
•
154 views
Netwitness RT - Don’t scratch that patch.pptx
Stefano Maccaglia
•
105 views
Getting your enterprise ready for Microsoft 365 Copilot
Vignesh Ganesan I Microsoft MVP
•
167 views
GDSC Cloud Lead Presentation.pptx
AbhinavNautiyal8
•
62 views
The Flutter Job Market At The Moment
Ahmed Abu Eldahab
•
21 views
Unleashing Innovation: IoT Project with MicroPython
Vubon Roy
•
35 views
info_session_gdsc_tmsl .pptx
NikitaSingh741518
•
34 views
Need for Speed: Removing speed bumps in API Projects
Łukasz Chruściel
•
103 views
Framing Few Shot Knowledge Graph Completion with Large Language Models
MODUL Technology GmbH
•
41 views
Scaling out with WordPress
Konstantin Kovshenin
•
58 views
Product Research Presentation-Maidy Veloso.pptx
MaidyVeloso
•
22 views
Future of Skills
Alison B. Lowndes
•
65 views
Cloud Composer workshop at Airflow Summit 2023.pdf
Leah Cole
•
89 views
Understanding Wireguard, TLS and Workload Identity
Christian Posta
•
175 views
GIT AND GITHUB (1).pptx
GDSCCVRGUPoweredbyGo
•
22 views
Elevate Your Enterprise with FME 23.1
Safe Software
•
376 views
LLaMA 2.pptx
RkRahul16
•
40 views
Call a C API from Python becomes more enjoyable with CFFI, Jean-Sébastien Bevilacqua
1.
CALL A C API FROM PYTHON BECOMES MORE ENJOYABLE WITH CFFI JEAN-SÉBASTIEN BEVILACQUA
2.
WHY PYTHON EXTENSION ?
3.
WHY PYTHON EXTENSION ? ACCESSING LOW-LEVEL API OPENGL / VULKAN
4.
WHY PYTHON EXTENSION ? LINKING TO EXISTING C LIBRARY
5.
WHY PYTHON EXTENSION ? IMPROVING PERFORMANCE
6.
OUR GOOD FRIEND IS ALWAYS HERE !
7.
I'M TOTALLY LOST WITH CPYTHON API
8.
APPLICATION PROGRAMMING INTERFACE APPLICATION BINARY INTERFACE
9.
WHY ABI ?
10.
CYTHON
11.
CYTHON INCREMENTAL OPTIMIZATION PY++
12.
CYTHON def fib(int n): cdef int a = 0 cdef int b = 1 while b < n: print(b) a, b = b, a + b
13.
CYTHON ABI / API
14.
CTYPES BUILT-IN / ABI ONLY
15.
CTYPES from ctypes import cdll, Structure, c_int, c_double lib = cdll.LoadLibrary('./vector.so') # ctypes Point structure class Point(Structure): _fields_ = [('x', c_int), ('y', c_int)] # Initialize Point[2] argument points_array = (Point * 2)((1, 2), (3, 4)) # Get vector_size from library vector_size_fn = lib.vector_size vector_size_fn.restype = c_double # Call vector_size with ctypes size = vector_size_fn(points_array) print('out = {}'.format(size))
16.
CFFI ENLIGHTENED IN-LINE : IMPORT TIME OUT-OF-LINE : INSTALL TIME
17.
ABI / IN-LINE from cffi import FFI ffi = FFI() ffi.cdef("int printf(const char *format, ...);") C = ffi.dlopen(None) arg = ffi.new("char[]", "world") C.printf("hello %sn", arg)
18.
ABI / IN-LINE DEMO
19.
API / OUT-OF-LINE from cffi import FFI ffibuilder = FFI() ffibuilder.set_source("_example", r"""#include <sys/types.h> #include <pwd.h> """) ffibuilder.cdef(""" struct passwd { char *pw_name; ...; }; struct passwd *getpwuid(int uid); """) if __name__ == "__main__": ffibuilder.compile(verbose=True)
20.
API / OUT-OF-LINE RUNNING
21.
REBUILD
22.
STATISTICS VULKAN API C HEADER : 5088 LOC XML DESCRIPTION : 6461 LOC
23.
STATISTICS C WRAPPER GENERATED C FILE : 62705 LOC GENERATOR : 1057 PY-LOC / 1141 C-LOC
24.
STATISTICS CFFI WRAPPER GENERATED PYTHON FILE : 4859 LOC GENERATOR : 692 PY-LOC
25.
HOW IT WORKS ?
26.
JINJA2 TEMPLATE
27.
JINJA2 TEMPLATEC EXTENSION ├── converters.c -> 423 ├── custom_functions.c -> 103 ├── custom_structs.c -> 59 ├── extension_functions.c -> 32 ├── functions.c -> 8 ├── header.c -> 11 ├── init.c -> 68 ├── init_unions │ ├── vkclearcolorvalue.c -> 69 │ └── vkclearvalue.c -> 36 ├── macros.c -> 111 ├── main.c -> 122 ├── objects.c -> 99 └── jfilter.py -> 542 Total: 1683
28.
JINJA2 TEMPLATE CFFI EXTENSION ONLY ONE SMALL FILE vulkan.template.py -> 340
29.
SHOW ME THE CODE !
30.
CONSTANTS C EXTENSION CFFI EXTENSION PyModule_AddIntConstant(module, {{name}}, {{value}}); {{name}} = {{value}}
31.
OBJECTS
32.
OBJECTS C EXTENSION NEW (MALLOC) DEL (FREE) INIT GET (FOR EACH MEMBER)
33.
OBJECTS CFFI EXTENSION def _new(ctype, **kwargs): _type = ffi.typeof(ctype) ptrs = {} for k, v in kwargs.items(): # convert tuple pair to dict ktype = dict(_type.fields)[k].type if ktype.kind == 'pointer': ptrs[k] = _cast_ptr(v, ktype) init = dict(kwargs, **{k: v for k, (v, _) in ptrs.items()}) return ffi.new(_type.cname + '*', init)[0]
34.
FAST API MODE
35.
SHADERC WRAPPER
36.
FOLDER DESIGN ├── _cffi_build │ ├── pyshaderc_build.py │ └── shaderc.h ├── pyshaderc │ └── __init__.py └── setup.py
37.
DEFINITION ffi = FFI() with open('shaderc.h') as f: ffi.cdef(f.read())
38.
BUILDING ffi = FFI() with open('shaderc.h') as f: source = f.read() ffi.set_source('_pyshaderc', source, libraries=['shaderc_combined']) if __name__ == '__main__': ffi.compile()
39.
USE
40.
USE from pyshaderc._pyshaderc import ffi, lib
41.
USE def compile_into_spirv(raw, stage, suppress_warnings=False): # initialize compiler compiler = lib.shaderc_compiler_initialize() # compile result = lib.shaderc_compile_into_spv(compiler, raw, len(raw), stage, b"main")
42.
USE length = lib.shaderc_result_get_length(result) output_pointer = lib.shaderc_result_get_bytes(result) tmp = bytearray(length) ffi.memmove(tmp, output_pointer, length) spirv = bytes(tmp) return spirv
43.
SETUPTOOLS INTEGRATION setup( ... cffi_modules=["_cffi_build/pyshaderc_build.py:ffi"] )
44.
DEMO TIME !
45.
GIVE A TRY TO CFFI ! @REALITIX LINAGORA.COM