SlideShare a Scribd company logo
CALL	A	C	API	FROM	PYTHON
BECOMES	MORE	ENJOYABLE	WITH
CFFI
JEAN-SÉBASTIEN	BEVILACQUA
WHY	PYTHON
EXTENSION	?
WHY	PYTHON
EXTENSION	?
ACCESSING	LOW-LEVEL	API	
OPENGL	/	VULKAN

WHY	PYTHON
EXTENSION	?
LINKING	TO	EXISTING	C	LIBRARY	

WHY	PYTHON
EXTENSION	?
IMPROVING	PERFORMANCE	

OUR	GOOD	FRIEND	IS
ALWAYS	HERE	!
I'M	TOTALLY	LOST	
WITH	
CPYTHON	API
APPLICATION	PROGRAMMING
INTERFACE
APPLICATION	BINARY	INTERFACE

WHY	ABI	?
CYTHON
CYTHON
INCREMENTAL	OPTIMIZATION	
PY++
CYTHON
def	fib(int	n):
				cdef	int	a	=	0
				cdef	int	b	=		1
				while	b	<	n:
								print(b)
								a,	b	=	b,	a	+	b
CYTHON
ABI	/	API
CTYPES
BUILT-IN	/	ABI	ONLY
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))
CFFI	ENLIGHTENED
IN-LINE	:	IMPORT	TIME
OUT-OF-LINE	:	INSTALL	TIME
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)
ABI	/	IN-LINE
DEMO
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)
API	/	OUT-OF-LINE
RUNNING
REBUILD
STATISTICS
VULKAN	API
C	HEADER	:	5088	LOC
XML	DESCRIPTION	:	6461	LOC
STATISTICS
C	WRAPPER
GENERATED	C	FILE	:	62705	LOC
GENERATOR	:	1057	PY-LOC	/	1141	C-LOC
STATISTICS
CFFI	WRAPPER
GENERATED	PYTHON	FILE	:	4859
LOC
GENERATOR	:	692	PY-LOC
HOW	IT	WORKS	?
JINJA2	TEMPLATE
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
JINJA2	TEMPLATE
CFFI	EXTENSION
ONLY	ONE	SMALL	FILE
vulkan.template.py	->	340
SHOW	ME	THE	CODE	!
CONSTANTS
C	EXTENSION
CFFI	EXTENSION
PyModule_AddIntConstant(module,	{{name}},	{{value}});
{{name}}	=	{{value}}
OBJECTS
OBJECTS
C	EXTENSION
NEW	(MALLOC)
DEL	(FREE)
INIT
GET	(FOR	EACH	MEMBER)
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]
FAST	API	MODE
SHADERC	WRAPPER
FOLDER	DESIGN
├──	_cffi_build
│			├──	pyshaderc_build.py
│			└──	shaderc.h
├──	pyshaderc
│			└──	__init__.py
└──	setup.py
DEFINITION
ffi	=	FFI()
with	open('shaderc.h')	as	f:
				ffi.cdef(f.read())
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()
USE
USE
from	pyshaderc._pyshaderc	import	ffi,	lib
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")
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
SETUPTOOLS
INTEGRATION
setup(
				...
				cffi_modules=["_cffi_build/pyshaderc_build.py:ffi"]
)
DEMO	TIME	!
GIVE	A	TRY	TO	CFFI	!
@REALITIX
LINAGORA.COM

More Related Content

PDF
Call a C API from Python becomes more enjoyable with CFFI
PDF
Cython - close to metal Python
PDF
Cling the llvm based interpreter
PDF
Cython compiler
KEY
Mypy pycon-fi-2012
PDF
Brief Introduction to Cython
PDF
OSIS19_IoT :Transparent remote connectivity to short-range IoT devices, by Na...
PDF
OSIS19_Cloud : SAFC: Scheduling and Allocation Framework for Containers in a ...
Call a C API from Python becomes more enjoyable with CFFI
Cython - close to metal Python
Cling the llvm based interpreter
Cython compiler
Mypy pycon-fi-2012
Brief Introduction to Cython
OSIS19_IoT :Transparent remote connectivity to short-range IoT devices, by Na...
OSIS19_Cloud : SAFC: Scheduling and Allocation Framework for Containers in a ...

More from Pôle Systematic Paris-Region (20)

PDF
OSIS19_Cloud : Qu’apporte l’observabilité à la gestion de configuration? par ...
PDF
OSIS19_Cloud : Performance and power management in virtualized data centers, ...
PDF
OSIS19_Cloud : Des objets dans le cloud, et qui y restent -- L'expérience du ...
PDF
OSIS19_Cloud : Attribution automatique de ressources pour micro-services, Alt...
PDF
OSIS19_IoT : State of the art in security for embedded systems and IoT, by Pi...
PDF
Osis19_IoT: Proof of Pointer Programs with Ownership in SPARK, by Yannick Moy
PDF
Osis18_Cloud : Pas de commun sans communauté ?
PDF
Osis18_Cloud : Projet Wolphin
PDF
Osis18_Cloud : Virtualisation efficace d’architectures NUMA
PDF
Osis18_Cloud : DeepTorrent Stockage distribué perenne basé sur Bittorrent
PDF
Osis18_Cloud : Software-heritage
PDF
OSIS18_IoT: L'approche machine virtuelle pour les microcontrôleurs, le projet...
PDF
OSIS18_IoT: La securite des objets connectes a bas cout avec l'os et riot
PDF
OSIS18_IoT : Solution de mise au point pour les systemes embarques, par Julio...
PDF
OSIS18_IoT : Securisation du reseau des objets connectes, par Nicolas LE SAUZ...
PDF
OSIS18_IoT : Ada and SPARK - Defense in Depth for Safe Micro-controller Progr...
PDF
OSIS18_IoT : RTEMS pour l'IoT professionnel, par Pierre Ficheux (Smile ECS)
PDF
PyParis 2017 / Un mooc python, by thierry parmentelat
PDF
PyParis2017 / Python pour les enseignants des classes préparatoires, by Olivi...
PDF
PyParis 2017 / Unicode and bytes demystified, by Boris Feld
OSIS19_Cloud : Qu’apporte l’observabilité à la gestion de configuration? par ...
OSIS19_Cloud : Performance and power management in virtualized data centers, ...
OSIS19_Cloud : Des objets dans le cloud, et qui y restent -- L'expérience du ...
OSIS19_Cloud : Attribution automatique de ressources pour micro-services, Alt...
OSIS19_IoT : State of the art in security for embedded systems and IoT, by Pi...
Osis19_IoT: Proof of Pointer Programs with Ownership in SPARK, by Yannick Moy
Osis18_Cloud : Pas de commun sans communauté ?
Osis18_Cloud : Projet Wolphin
Osis18_Cloud : Virtualisation efficace d’architectures NUMA
Osis18_Cloud : DeepTorrent Stockage distribué perenne basé sur Bittorrent
Osis18_Cloud : Software-heritage
OSIS18_IoT: L'approche machine virtuelle pour les microcontrôleurs, le projet...
OSIS18_IoT: La securite des objets connectes a bas cout avec l'os et riot
OSIS18_IoT : Solution de mise au point pour les systemes embarques, par Julio...
OSIS18_IoT : Securisation du reseau des objets connectes, par Nicolas LE SAUZ...
OSIS18_IoT : Ada and SPARK - Defense in Depth for Safe Micro-controller Progr...
OSIS18_IoT : RTEMS pour l'IoT professionnel, par Pierre Ficheux (Smile ECS)
PyParis 2017 / Un mooc python, by thierry parmentelat
PyParis2017 / Python pour les enseignants des classes préparatoires, by Olivi...
PyParis 2017 / Unicode and bytes demystified, by Boris Feld
Ad

Recently uploaded (20)

PPT
Teaching material agriculture food technology
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Electronic commerce courselecture one. Pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Encapsulation theory and applications.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
KodekX | Application Modernization Development
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Approach and Philosophy of On baking technology
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Teaching material agriculture food technology
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Electronic commerce courselecture one. Pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Encapsulation theory and applications.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Per capita expenditure prediction using model stacking based on satellite ima...
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Review of recent advances in non-invasive hemoglobin estimation
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Mobile App Security Testing_ A Comprehensive Guide.pdf
KodekX | Application Modernization Development
Dropbox Q2 2025 Financial Results & Investor Presentation
Approach and Philosophy of On baking technology
Agricultural_Statistics_at_a_Glance_2022_0.pdf
MYSQL Presentation for SQL database connectivity
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Ad

Call a C API from Python becomes more enjoyable with CFFI, Jean-Sébastien Bevilacqua