SlideShare a Scribd company logo
CALL	A	C	API	FROM	PYTHON
BECOMES	MORE	ENJOYABLE	WITH
CFFI
JEAN-SÉBASTIEN	BEVILACQUA
/ME
twitter/@realitix
github.com/realitix
realitix.github.io
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	!
SPECIAL	GUEST
ARMIN	RIGO	
MACIEJ	FIJAŁKOWSKI
GIVE	A	TRY	TO	CFFI	!
@REALITIX
LINAGORA.COM

More Related Content

PDF
Call a C API from Python becomes more enjoyable with CFFI, Jean-Sébastien Bev...
PDF
Extending Python - EuroPython 2014
PDF
Extending Python - FOSDEM 2015
PDF
Development_C_Extension_with_Pybind11.pdf
ODP
C Types - Extending Python
PDF
OpenSAF Symposium_Python Bindings_9.21.11
PDF
Extending Python, what is the best option for me?
PDF
Extending Python - Codemotion Milano 2014
Call a C API from Python becomes more enjoyable with CFFI, Jean-Sébastien Bev...
Extending Python - EuroPython 2014
Extending Python - FOSDEM 2015
Development_C_Extension_with_Pybind11.pdf
C Types - Extending Python
OpenSAF Symposium_Python Bindings_9.21.11
Extending Python, what is the best option for me?
Extending Python - Codemotion Milano 2014

Similar to Call a C API from Python becomes more enjoyable with CFFI (20)

PDF
Cluj.py Meetup: Extending Python in C
PDF
20240921 - HITCON 社群活動《CTF 轉生-到了業界就拿出真本事》- bruce30262 講師分享
PDF
Extending Python with ctypes
PDF
PyParis 2017 / Writing a C Python extension in 2017, Jean-Baptiste Aviat
PDF
Interfacing C++ with Python to boost your legacy apps with Python interfaces
PDF
Build and deploy scientific Python Applications
PDF
PyCon2022 - Building Python Extensions
PDF
A CTF Hackers Toolbox
PDF
Pybind11 - SciPy 2021
PDF
Notes about moving from python to c++ py contw 2020
PDF
DEF CON 27 - DANIEL ROMERO and MARIO RIVAS - why you should fear your mundane...
PDF
The Python in the Apple
PPTX
Kostiantyn Grygoriev "Wrapping C++ for Python"
PDF
[GSoC 2017] gopy: Updating gopy to support Python3 and PyPy
PPTX
Ctypes
PDF
SunPy: Python for solar physics
PPTX
Steelcon 2015 - 0wning the internet of trash
PDF
Writing a Python C extension
PDF
Harmonic Stack for Speed
PPTX
Advanced Internet of Things firmware engineering with Thingsquare and Contiki...
Cluj.py Meetup: Extending Python in C
20240921 - HITCON 社群活動《CTF 轉生-到了業界就拿出真本事》- bruce30262 講師分享
Extending Python with ctypes
PyParis 2017 / Writing a C Python extension in 2017, Jean-Baptiste Aviat
Interfacing C++ with Python to boost your legacy apps with Python interfaces
Build and deploy scientific Python Applications
PyCon2022 - Building Python Extensions
A CTF Hackers Toolbox
Pybind11 - SciPy 2021
Notes about moving from python to c++ py contw 2020
DEF CON 27 - DANIEL ROMERO and MARIO RIVAS - why you should fear your mundane...
The Python in the Apple
Kostiantyn Grygoriev "Wrapping C++ for Python"
[GSoC 2017] gopy: Updating gopy to support Python3 and PyPy
Ctypes
SunPy: Python for solar physics
Steelcon 2015 - 0wning the internet of trash
Writing a Python C extension
Harmonic Stack for Speed
Advanced Internet of Things firmware engineering with Thingsquare and Contiki...
Ad

More from LINAGORA (20)

PDF
Personal branding : e-recrutement et réseaux sociaux professionnels
PDF
Construisons ensemble le chatbot bancaire dedemain !
PDF
ChatBots et intelligence artificielle arrivent dans les banques
PDF
Deep Learning in practice : Speech recognition and beyond - Meetup
PDF
Advanced Node.JS Meetup
PDF
[UDS] Cloud Computing "pour les nuls" (Exemple avec LinShare)
PDF
Angular v2 et plus : le futur du développement d'applications en entreprise
PDF
Comment faire ses mappings ElasticSearch aux petits oignons ? - LINAGORA
PDF
Angular (v2 and up) - Morning to understand - Linagora
PDF
Industrialisez le développement et la maintenance de vos sites avec Drupal
PDF
CapDémat Evolution plateforme de GRU pour collectivités
PDF
Présentation du marché P2I UGAP « Support sur Logiciels Libres »
PDF
Offre de demat d'Adullact projet
PDF
La dématérialisation du conseil minicipal
PDF
Open stack @ sierra wireless
PDF
OpenStack - open source au service du Cloud
PDF
Architecture d'annuaire hautement disponible avec OpenLDAP
PDF
Présentation offre LINID
PDF
Matinée pour conmrendre consacrée à LinID.org, gestion, fédération et contrôl...
PDF
Matinée pour conmrendre consacrée à LinShare.org, application de partage de f...
Personal branding : e-recrutement et réseaux sociaux professionnels
Construisons ensemble le chatbot bancaire dedemain !
ChatBots et intelligence artificielle arrivent dans les banques
Deep Learning in practice : Speech recognition and beyond - Meetup
Advanced Node.JS Meetup
[UDS] Cloud Computing "pour les nuls" (Exemple avec LinShare)
Angular v2 et plus : le futur du développement d'applications en entreprise
Comment faire ses mappings ElasticSearch aux petits oignons ? - LINAGORA
Angular (v2 and up) - Morning to understand - Linagora
Industrialisez le développement et la maintenance de vos sites avec Drupal
CapDémat Evolution plateforme de GRU pour collectivités
Présentation du marché P2I UGAP « Support sur Logiciels Libres »
Offre de demat d'Adullact projet
La dématérialisation du conseil minicipal
Open stack @ sierra wireless
OpenStack - open source au service du Cloud
Architecture d'annuaire hautement disponible avec OpenLDAP
Présentation offre LINID
Matinée pour conmrendre consacrée à LinID.org, gestion, fédération et contrôl...
Matinée pour conmrendre consacrée à LinShare.org, application de partage de f...
Ad

Recently uploaded (20)

PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
KodekX | Application Modernization Development
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
Spectroscopy.pptx food analysis technology
PDF
Empathic Computing: Creating Shared Understanding
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
“AI and Expert System Decision Support & Business Intelligence Systems”
Dropbox Q2 2025 Financial Results & Investor Presentation
Understanding_Digital_Forensics_Presentation.pptx
Reach Out and Touch Someone: Haptics and Empathic Computing
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Programs and apps: productivity, graphics, security and other tools
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Review of recent advances in non-invasive hemoglobin estimation
20250228 LYD VKU AI Blended-Learning.pptx
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
MIND Revenue Release Quarter 2 2025 Press Release
KodekX | Application Modernization Development
Mobile App Security Testing_ A Comprehensive Guide.pdf
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Spectroscopy.pptx food analysis technology
Empathic Computing: Creating Shared Understanding

Call a C API from Python becomes more enjoyable with CFFI