SlideShare ist ein Scribd-Unternehmen logo
1 von 45
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Mehr von Pôle Systematic Paris-Region

Mehr von Pôle Systematic Paris-Region (20)

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

Kürzlich hochgeladen

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Kürzlich hochgeladen (20)

Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 

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