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

More from LINAGORA (20)

PDF
Comment faire ses mappings ElasticSearch aux petits oignons ? - LINAGORA
LINAGORA
 
PDF
Angular (v2 and up) - Morning to understand - Linagora
LINAGORA
 
PDF
Industrialisez le développement et la maintenance de vos sites avec Drupal
LINAGORA
 
PDF
CapDémat Evolution plateforme de GRU pour collectivités
LINAGORA
 
PDF
Présentation du marché P2I UGAP « Support sur Logiciels Libres »
LINAGORA
 
PDF
Offre de demat d'Adullact projet
LINAGORA
 
PDF
La dématérialisation du conseil minicipal
LINAGORA
 
PDF
Open stack @ sierra wireless
LINAGORA
 
PDF
OpenStack - open source au service du Cloud
LINAGORA
 
PDF
Architecture d'annuaire hautement disponible avec OpenLDAP
LINAGORA
 
PDF
Présentation offre LINID
LINAGORA
 
PDF
Matinée pour conmrendre consacrée à LinID.org, gestion, fédération et contrôl...
LINAGORA
 
PDF
Matinée pour conmrendre consacrée à LinShare.org, application de partage de f...
LINAGORA
 
PDF
Open Source Software Assurance by Linagora
LINAGORA
 
PDF
Présentation de l’extension Lightning pour Thunderbird
LINAGORA
 
PDF
Présentation de la nouvelle version de Mozilla Thunderbird
LINAGORA
 
PDF
Présentation de la roadmap OBM, 28 août 2012
LINAGORA
 
PDF
Présentation séminaire novembre 2011 - Drupal 7 / Drupal commerce
LINAGORA
 
PDF
Découvrir Drupal, le CMS Open Source de référence
LINAGORA
 
PDF
Séminaire gratuit : OBM 2.4 - nouveautés, intégration et cloud !
LINAGORA
 
Comment faire ses mappings ElasticSearch aux petits oignons ? - LINAGORA
LINAGORA
 
Angular (v2 and up) - Morning to understand - Linagora
LINAGORA
 
Industrialisez le développement et la maintenance de vos sites avec Drupal
LINAGORA
 
CapDémat Evolution plateforme de GRU pour collectivités
LINAGORA
 
Présentation du marché P2I UGAP « Support sur Logiciels Libres »
LINAGORA
 
Offre de demat d'Adullact projet
LINAGORA
 
La dématérialisation du conseil minicipal
LINAGORA
 
Open stack @ sierra wireless
LINAGORA
 
OpenStack - open source au service du Cloud
LINAGORA
 
Architecture d'annuaire hautement disponible avec OpenLDAP
LINAGORA
 
Présentation offre LINID
LINAGORA
 
Matinée pour conmrendre consacrée à LinID.org, gestion, fédération et contrôl...
LINAGORA
 
Matinée pour conmrendre consacrée à LinShare.org, application de partage de f...
LINAGORA
 
Open Source Software Assurance by Linagora
LINAGORA
 
Présentation de l’extension Lightning pour Thunderbird
LINAGORA
 
Présentation de la nouvelle version de Mozilla Thunderbird
LINAGORA
 
Présentation de la roadmap OBM, 28 août 2012
LINAGORA
 
Présentation séminaire novembre 2011 - Drupal 7 / Drupal commerce
LINAGORA
 
Découvrir Drupal, le CMS Open Source de référence
LINAGORA
 
Séminaire gratuit : OBM 2.4 - nouveautés, intégration et cloud !
LINAGORA
 

Recently uploaded (20)

PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PPTX
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
Python basic programing language for automation
DanialHabibi2
 
PDF
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PPT
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PPTX
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Python basic programing language for automation
DanialHabibi2
 
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Ad

Call a C API from Python becomes more enjoyable with CFFI