SlideShare uma empresa Scribd logo
1 de 47
Baixar para ler offline
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

Mais conteúdo relacionado

Mais de LINAGORA

Présentation offre LINID
Présentation offre LINIDPrésentation offre LINID
Présentation offre LINID
LINAGORA
 

Mais de LINAGORA (20)

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

Último

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 

Call a C API from Python becomes more enjoyable with CFFI