SlideShare ist ein Scribd-Unternehmen logo
1 von 35
Python Bindings Overview RudáMoura : ruda.moura@gmail.com Sébastien Tandel : sebastien.tandel@gmail.com
Python C API PythonBrasil[5] Caxias do Sul, RS - Brazil
3 Python C API : philosophy Everything is a PyObject* Public symbols with Py prefix Private symbols with _Py prefix Objects are stored in memory heap It’s you job to count the references Py_INCREF & Py_DECREF Yeah, that’s sucks! There are functions to convert C data types to Python C data types and back PyArg_ParseTuple() Py_BuildValue()
Python C API A wrapper around two readline functions: readline - return a malloced string add_history - add a (const) string to the history char *readline(const char *); intadd_history(const char *);
Python C API readline() #include <Python.h> #include <readline/readline.h> PyObject * fn_readline(PyObject *self, PyObject *args) {   char *prompt;   char *line; PyObject *o;   if (!PyArg_ParseTuple(args, "s", &prompt))     return NULL; line = readline(prompt); o = Py_BuildValue("s", line); free(line);   return o; }
Python C API add_history() PyObject * fn_add_history(PyObject *self, PyObject *args) {   char *line; int status; PyObject *o;   if (!PyArg_ParseTuple(args, "s", &line))  return NULL; status = add_history(line); o = Py_BuildValue("i", status);   return o; } And if I want to return None? Py_INCREF(Py_None);  return Py_None;
Python C API Registering functions and modules static PyMethodDef methods[] = {   {"readline", fn_readline, METH_VARARGS, NULL},   {"add_history", fn_add_history, METH_VARARGS, NULL},   {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initreadline(void) {   (void) Py_InitModule("readline", methods); }
Python C API Compiling... $ gcc -dynamiclib -I/usr/include/python2.5 -lpython -lreadline mod_readline.c -o readline.so Or you can use distutils / setup.py
Python C API The goods Strong C/C++ and Python integration The best performance possible Full Python data types support The bads It’s hard work, only good for masochists You’re supposed to be good in C Reference counts nightmare
Python C API : summary
SWIG Simplified Wrapper and Interface Generator
SWIG : philosophy Everything is defined in the interface file Module name Literal #include or source code Define What symbols to export The swig compiler translates the interface file into C source code
SWIG The interface file // readline.i %module readline %{ #include <readline/readline.h> %} char *readline(const char *); intadd_history(const char *);
SWIG Compiling... $ swig -python readline.i $ gcc -creadline_wrap.c  -I/usr/include/python2.5 $ gcc -dynamiclibreadline_wrap.o -lpython -lreadline -o _readline.so Or you can use distutils / setup.py
SWIG The goods Full bindings process automatization Strong C++ support (class, template, exception) Not only for Python! Support for Perl, Ruby and others It’s mature (since 1995) The bads The C file created is not for human consum Callbacks and double references are not easy
SWIG : summary
CTYPES
Ctypes : philosophy Ctypes is a dlopen-like for Python The basic steps : Obtain a handle of a library Use this handle to access library’s functions from ctypes import cdll libc_h = cdll.LoadLibrary(“libc.so.6”) libc_h.mkdir(“python-mkdir-test”)
Ctypes OK, it’s a dlopen-like, and? libc_h.mkdir(“python-mkdir-test”) ,[object Object],Transparent conversion for these types : None, integers, long, byte strings and unicode strings
Ctypes What if I want specific C types? c_int, c_long, c_char, c_short, c_ulong, … i = c_int(10) print i.value() 10
Ctypes Functions return values? By default, assumed to be int from ctypes import cdll, c_char_p lr = cdll.LoadLibrary("libreadline.dylib") while True:   line = lr.readline(“C:>") c_line = c_char_p(line)   if not c_line.value: break
Ctypes Return value as input for another C function? from ctypes import cdll, c_char_p lr = cdll.LoadLibrary("libreadline.dylib") while True:   line = lr.readline(“C:>") c_line = c_char_p(line)   if not c_line.value: break lr.add_history(c_line.value)  # or lr.add_history(c_line) 	  # or lr.add_history(line)
Ctypes Is there a way to simplify a bit? from ctypes import cdll, c_char_p lr = cdll.LoadLibrary("libreadline.dylib") lr.readline.restype = c_char_p while True:   line = lr.readline("c:>")   if not line: break lr.add_history(line) You can define types for arguments too with .argtypes!
Ctypes Possible to access structures returned by C functions Possible to define arrays … but with a fixed length! Possible to create callback written in Python called by C lib. On windows, check the number of parameters passed to a function. Part of Python 2.5
Ctypes : summary
Cython
Cython : philosophy Cython is an extension of Python language Three simple steps : Write “python” Compile the module it with C compiler Import the package in your python code
Cython Compiling a module => setuptools print “hello world!” setup.py from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext setup( cmdclass = {'build_ext': build_ext}, ext_modules = [Extension(”hello", [”hello.pyx"])] )
Cython cdef extern from "readline/readline.h":   char* readline(char*) intadd_history(char*) def readline_loop():   while True:     line = readline("c:>”)     if not line: break add_history(line)
Cython setup.py from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext setup( cmdclass = {'build_ext': build_ext}, ext_modules = [Extension(‘readlineloop’,  			    [‘readline-loop.pyx’], libraries = [‘readline’])] )
Cython Last details : Can access C structures Possible to define callbacks Check on number of args Possible to wrap C++ classes! Handle exceptions! Can be used to optimize your code ,[object Object],[object Object]
Cython : summary
Conclusions
Thank You! ruda.moura@gmail.com sebastien.tandel@gmail.com
Python Bindings Overview

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

C++ vs python the best ever comparison
C++ vs python the best ever comparison C++ vs python the best ever comparison
C++ vs python the best ever comparison
 
C++ vs python
C++ vs pythonC++ vs python
C++ vs python
 
C tutorials
C tutorialsC tutorials
C tutorials
 
GNU GCC - what just a compiler...?
GNU GCC - what just a compiler...?GNU GCC - what just a compiler...?
GNU GCC - what just a compiler...?
 
C introduction by piyushkumar
C introduction by piyushkumarC introduction by piyushkumar
C introduction by piyushkumar
 
C++ vs C#
C++ vs C#C++ vs C#
C++ vs C#
 
Introduction to c programming language
Introduction to c programming languageIntroduction to c programming language
Introduction to c programming language
 
Comparison between python and c++
Comparison between python and c++Comparison between python and c++
Comparison between python and c++
 
علم البيانات - Data Sience
علم البيانات - Data Sience علم البيانات - Data Sience
علم البيانات - Data Sience
 
Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1
 
Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1Csc1100 lecture01 ch01-pt1
Csc1100 lecture01 ch01-pt1
 
C under Linux
C under LinuxC under Linux
C under Linux
 
Intro of C
Intro of CIntro of C
Intro of C
 
History of c++
History of c++History of c++
History of c++
 
C fundamentals
C fundamentalsC fundamentals
C fundamentals
 
Cs gate-2011
Cs gate-2011Cs gate-2011
Cs gate-2011
 
R and Python, A Code Demo
R and Python, A Code DemoR and Python, A Code Demo
R and Python, A Code Demo
 
The Python Programming Language and HDF5: H5Py
The Python Programming Language and HDF5: H5PyThe Python Programming Language and HDF5: H5Py
The Python Programming Language and HDF5: H5Py
 
Lecture01
Lecture01Lecture01
Lecture01
 
Substituting HDF5 tools with Python/H5py scripts
Substituting HDF5 tools with Python/H5py scriptsSubstituting HDF5 tools with Python/H5py scripts
Substituting HDF5 tools with Python/H5py scripts
 

Andere mochten auch

Blockchain overview, use cases, implementations and challenges
Blockchain overview, use cases, implementations and challengesBlockchain overview, use cases, implementations and challenges
Blockchain overview, use cases, implementations and challengesSébastien Tandel
 
ACI Mercato auto usate novembre 2012
ACI Mercato auto usate novembre 2012ACI Mercato auto usate novembre 2012
ACI Mercato auto usate novembre 2012autoblogpuntoit
 
Listino Prezzi McLaren 570GT
Listino Prezzi McLaren 570GTListino Prezzi McLaren 570GT
Listino Prezzi McLaren 570GTAutoblog.it
 
SWIG Hello World
SWIG Hello WorldSWIG Hello World
SWIG Hello Worlde8xu
 
Using SWIG to Control, Prototype, and Debug C Programs with Python
Using SWIG to Control, Prototype, and Debug C Programs with PythonUsing SWIG to Control, Prototype, and Debug C Programs with Python
Using SWIG to Control, Prototype, and Debug C Programs with PythonDavid Beazley (Dabeaz LLC)
 
SWIG : An Easy to Use Tool for Integrating Scripting Languages with C and C++
SWIG : An Easy to Use Tool for Integrating Scripting Languages with C and C++SWIG : An Easy to Use Tool for Integrating Scripting Languages with C and C++
SWIG : An Easy to Use Tool for Integrating Scripting Languages with C and C++David Beazley (Dabeaz LLC)
 
Brussels Hyperledger Meetup - IBM Blockchain Explained
Brussels Hyperledger Meetup - IBM Blockchain ExplainedBrussels Hyperledger Meetup - IBM Blockchain Explained
Brussels Hyperledger Meetup - IBM Blockchain ExplainedDavid Smits
 
Blockchain for Business
Blockchain for BusinessBlockchain for Business
Blockchain for BusinessFloyd DCosta
 
Bitcoin, Blockchain, and IoT
Bitcoin, Blockchain, and IoTBitcoin, Blockchain, and IoT
Bitcoin, Blockchain, and IoTRobin Teigland
 
Industria 4.0 e IoT: Panorama, Leggende e Standard
Industria 4.0 e IoT: Panorama, Leggende e StandardIndustria 4.0 e IoT: Panorama, Leggende e Standard
Industria 4.0 e IoT: Panorama, Leggende e Standarduninfoit
 
Blockchain Perspective - Internet of Memorable Things
Blockchain Perspective - Internet of Memorable ThingsBlockchain Perspective - Internet of Memorable Things
Blockchain Perspective - Internet of Memorable ThingsTim Lackey
 
Practical Applications of Block Chain Technologies
Practical Applications of Block Chain Technologies Practical Applications of Block Chain Technologies
Practical Applications of Block Chain Technologies Priyanka Aash
 
170321 cebit blockchain summit frank bolten
170321 cebit blockchain summit frank bolten170321 cebit blockchain summit frank bolten
170321 cebit blockchain summit frank boltenFrank Bolten
 
State of Blockchain Q4 2016
State of Blockchain Q4 2016State of Blockchain Q4 2016
State of Blockchain Q4 2016CoinDesk
 
The design thinking transformation in business
The design thinking transformation in businessThe design thinking transformation in business
The design thinking transformation in businessCathy Wang
 
Blockchain in IoT and Other Considerations by Dinis Guarda
Blockchain in IoT and Other Considerations by Dinis GuardaBlockchain in IoT and Other Considerations by Dinis Guarda
Blockchain in IoT and Other Considerations by Dinis GuardaDinis Guarda
 
The Top Skills That Can Get You Hired in 2017
The Top Skills That Can Get You Hired in 2017The Top Skills That Can Get You Hired in 2017
The Top Skills That Can Get You Hired in 2017LinkedIn
 

Andere mochten auch (19)

Blockchain overview, use cases, implementations and challenges
Blockchain overview, use cases, implementations and challengesBlockchain overview, use cases, implementations and challenges
Blockchain overview, use cases, implementations and challenges
 
ACI Mercato auto usate novembre 2012
ACI Mercato auto usate novembre 2012ACI Mercato auto usate novembre 2012
ACI Mercato auto usate novembre 2012
 
Listino Prezzi McLaren 570GT
Listino Prezzi McLaren 570GTListino Prezzi McLaren 570GT
Listino Prezzi McLaren 570GT
 
Python For Large Company?
Python For Large Company?Python For Large Company?
Python For Large Company?
 
SWIG Hello World
SWIG Hello WorldSWIG Hello World
SWIG Hello World
 
Using SWIG to Control, Prototype, and Debug C Programs with Python
Using SWIG to Control, Prototype, and Debug C Programs with PythonUsing SWIG to Control, Prototype, and Debug C Programs with Python
Using SWIG to Control, Prototype, and Debug C Programs with Python
 
SWIG : An Easy to Use Tool for Integrating Scripting Languages with C and C++
SWIG : An Easy to Use Tool for Integrating Scripting Languages with C and C++SWIG : An Easy to Use Tool for Integrating Scripting Languages with C and C++
SWIG : An Easy to Use Tool for Integrating Scripting Languages with C and C++
 
Interfacing C/C++ and Python with SWIG
Interfacing C/C++ and Python with SWIGInterfacing C/C++ and Python with SWIG
Interfacing C/C++ and Python with SWIG
 
Brussels Hyperledger Meetup - IBM Blockchain Explained
Brussels Hyperledger Meetup - IBM Blockchain ExplainedBrussels Hyperledger Meetup - IBM Blockchain Explained
Brussels Hyperledger Meetup - IBM Blockchain Explained
 
Blockchain for Business
Blockchain for BusinessBlockchain for Business
Blockchain for Business
 
Bitcoin, Blockchain, and IoT
Bitcoin, Blockchain, and IoTBitcoin, Blockchain, and IoT
Bitcoin, Blockchain, and IoT
 
Industria 4.0 e IoT: Panorama, Leggende e Standard
Industria 4.0 e IoT: Panorama, Leggende e StandardIndustria 4.0 e IoT: Panorama, Leggende e Standard
Industria 4.0 e IoT: Panorama, Leggende e Standard
 
Blockchain Perspective - Internet of Memorable Things
Blockchain Perspective - Internet of Memorable ThingsBlockchain Perspective - Internet of Memorable Things
Blockchain Perspective - Internet of Memorable Things
 
Practical Applications of Block Chain Technologies
Practical Applications of Block Chain Technologies Practical Applications of Block Chain Technologies
Practical Applications of Block Chain Technologies
 
170321 cebit blockchain summit frank bolten
170321 cebit blockchain summit frank bolten170321 cebit blockchain summit frank bolten
170321 cebit blockchain summit frank bolten
 
State of Blockchain Q4 2016
State of Blockchain Q4 2016State of Blockchain Q4 2016
State of Blockchain Q4 2016
 
The design thinking transformation in business
The design thinking transformation in businessThe design thinking transformation in business
The design thinking transformation in business
 
Blockchain in IoT and Other Considerations by Dinis Guarda
Blockchain in IoT and Other Considerations by Dinis GuardaBlockchain in IoT and Other Considerations by Dinis Guarda
Blockchain in IoT and Other Considerations by Dinis Guarda
 
The Top Skills That Can Get You Hired in 2017
The Top Skills That Can Get You Hired in 2017The Top Skills That Can Get You Hired in 2017
The Top Skills That Can Get You Hired in 2017
 

Ähnlich wie Python Bindings Overview

Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programmingAlpana Gupta
 
Boost.Python: C++ and Python Integration
Boost.Python: C++ and Python IntegrationBoost.Python: C++ and Python Integration
Boost.Python: C++ and Python IntegrationGlobalLogic Ukraine
 
Zpugdccherry 101105081729-phpapp01
Zpugdccherry 101105081729-phpapp01Zpugdccherry 101105081729-phpapp01
Zpugdccherry 101105081729-phpapp01Jeffrey Clark
 
00 C hello world.pptx
00 C hello world.pptx00 C hello world.pptx
00 C hello world.pptxCarla227537
 
88 c programs 15184
88 c programs 1518488 c programs 15184
88 c programs 15184Sumit Saini
 
Cython - close to metal Python
Cython - close to metal PythonCython - close to metal Python
Cython - close to metal PythonTaras Lyapun
 
C Programming UNIT 1.pptx
C Programming  UNIT 1.pptxC Programming  UNIT 1.pptx
C Programming UNIT 1.pptxMugilvannan11
 
C language introduction geeksfor geeks
C language introduction   geeksfor geeksC language introduction   geeksfor geeks
C language introduction geeksfor geeksAashutoshChhedavi
 
C prog ppt
C prog pptC prog ppt
C prog pptxinoe
 
PyCon2022 - Building Python Extensions
PyCon2022 - Building Python ExtensionsPyCon2022 - Building Python Extensions
PyCon2022 - Building Python ExtensionsHenry Schreiner
 
Writing a Python C extension
Writing a Python C extensionWriting a Python C extension
Writing a Python C extensionSqreen
 

Ähnlich wie Python Bindings Overview (20)

Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
Boost.Python: C++ and Python Integration
Boost.Python: C++ and Python IntegrationBoost.Python: C++ and Python Integration
Boost.Python: C++ and Python Integration
 
Zpugdccherry 101105081729-phpapp01
Zpugdccherry 101105081729-phpapp01Zpugdccherry 101105081729-phpapp01
Zpugdccherry 101105081729-phpapp01
 
C Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.comC Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.com
 
00 C hello world.pptx
00 C hello world.pptx00 C hello world.pptx
00 C hello world.pptx
 
88 c programs 15184
88 c programs 1518488 c programs 15184
88 c programs 15184
 
88 c-programs
88 c-programs88 c-programs
88 c-programs
 
SRAVANByCPP
SRAVANByCPPSRAVANByCPP
SRAVANByCPP
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
Cython - close to metal Python
Cython - close to metal PythonCython - close to metal Python
Cython - close to metal Python
 
C Programming UNIT 1.pptx
C Programming  UNIT 1.pptxC Programming  UNIT 1.pptx
C Programming UNIT 1.pptx
 
C language introduction geeksfor geeks
C language introduction   geeksfor geeksC language introduction   geeksfor geeks
C language introduction geeksfor geeks
 
Basic c
Basic cBasic c
Basic c
 
Csdfsadf
CsdfsadfCsdfsadf
Csdfsadf
 
C
CC
C
 
C
CC
C
 
C prog ppt
C prog pptC prog ppt
C prog ppt
 
PyCon2022 - Building Python Extensions
PyCon2022 - Building Python ExtensionsPyCon2022 - Building Python Extensions
PyCon2022 - Building Python Extensions
 
Prog1-L1.pdf
Prog1-L1.pdfProg1-L1.pdf
Prog1-L1.pdf
 
Writing a Python C extension
Writing a Python C extensionWriting a Python C extension
Writing a Python C extension
 

Kürzlich hochgeladen

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 MenDelhi Call girls
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
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 MenDelhi Call girls
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
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 2024Rafal Los
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
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.pptxKatpro Technologies
 
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...Martijn de Jong
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
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 BusinessPixlogix Infotech
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 

Kürzlich hochgeladen (20)

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
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
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
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
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
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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
 
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...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 

Python Bindings Overview

  • 1. Python Bindings Overview RudáMoura : ruda.moura@gmail.com Sébastien Tandel : sebastien.tandel@gmail.com
  • 2. Python C API PythonBrasil[5] Caxias do Sul, RS - Brazil
  • 3. 3 Python C API : philosophy Everything is a PyObject* Public symbols with Py prefix Private symbols with _Py prefix Objects are stored in memory heap It’s you job to count the references Py_INCREF & Py_DECREF Yeah, that’s sucks! There are functions to convert C data types to Python C data types and back PyArg_ParseTuple() Py_BuildValue()
  • 4. Python C API A wrapper around two readline functions: readline - return a malloced string add_history - add a (const) string to the history char *readline(const char *); intadd_history(const char *);
  • 5. Python C API readline() #include <Python.h> #include <readline/readline.h> PyObject * fn_readline(PyObject *self, PyObject *args) { char *prompt; char *line; PyObject *o; if (!PyArg_ParseTuple(args, "s", &prompt)) return NULL; line = readline(prompt); o = Py_BuildValue("s", line); free(line); return o; }
  • 6. Python C API add_history() PyObject * fn_add_history(PyObject *self, PyObject *args) { char *line; int status; PyObject *o; if (!PyArg_ParseTuple(args, "s", &line)) return NULL; status = add_history(line); o = Py_BuildValue("i", status); return o; } And if I want to return None? Py_INCREF(Py_None); return Py_None;
  • 7. Python C API Registering functions and modules static PyMethodDef methods[] = { {"readline", fn_readline, METH_VARARGS, NULL}, {"add_history", fn_add_history, METH_VARARGS, NULL}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initreadline(void) { (void) Py_InitModule("readline", methods); }
  • 8. Python C API Compiling... $ gcc -dynamiclib -I/usr/include/python2.5 -lpython -lreadline mod_readline.c -o readline.so Or you can use distutils / setup.py
  • 9. Python C API The goods Strong C/C++ and Python integration The best performance possible Full Python data types support The bads It’s hard work, only good for masochists You’re supposed to be good in C Reference counts nightmare
  • 10. Python C API : summary
  • 11. SWIG Simplified Wrapper and Interface Generator
  • 12. SWIG : philosophy Everything is defined in the interface file Module name Literal #include or source code Define What symbols to export The swig compiler translates the interface file into C source code
  • 13. SWIG The interface file // readline.i %module readline %{ #include <readline/readline.h> %} char *readline(const char *); intadd_history(const char *);
  • 14. SWIG Compiling... $ swig -python readline.i $ gcc -creadline_wrap.c -I/usr/include/python2.5 $ gcc -dynamiclibreadline_wrap.o -lpython -lreadline -o _readline.so Or you can use distutils / setup.py
  • 15. SWIG The goods Full bindings process automatization Strong C++ support (class, template, exception) Not only for Python! Support for Perl, Ruby and others It’s mature (since 1995) The bads The C file created is not for human consum Callbacks and double references are not easy
  • 18. Ctypes : philosophy Ctypes is a dlopen-like for Python The basic steps : Obtain a handle of a library Use this handle to access library’s functions from ctypes import cdll libc_h = cdll.LoadLibrary(“libc.so.6”) libc_h.mkdir(“python-mkdir-test”)
  • 19.
  • 20. Ctypes What if I want specific C types? c_int, c_long, c_char, c_short, c_ulong, … i = c_int(10) print i.value() 10
  • 21. Ctypes Functions return values? By default, assumed to be int from ctypes import cdll, c_char_p lr = cdll.LoadLibrary("libreadline.dylib") while True: line = lr.readline(“C:>") c_line = c_char_p(line) if not c_line.value: break
  • 22. Ctypes Return value as input for another C function? from ctypes import cdll, c_char_p lr = cdll.LoadLibrary("libreadline.dylib") while True: line = lr.readline(“C:>") c_line = c_char_p(line) if not c_line.value: break lr.add_history(c_line.value) # or lr.add_history(c_line) # or lr.add_history(line)
  • 23. Ctypes Is there a way to simplify a bit? from ctypes import cdll, c_char_p lr = cdll.LoadLibrary("libreadline.dylib") lr.readline.restype = c_char_p while True: line = lr.readline("c:>") if not line: break lr.add_history(line) You can define types for arguments too with .argtypes!
  • 24. Ctypes Possible to access structures returned by C functions Possible to define arrays … but with a fixed length! Possible to create callback written in Python called by C lib. On windows, check the number of parameters passed to a function. Part of Python 2.5
  • 27. Cython : philosophy Cython is an extension of Python language Three simple steps : Write “python” Compile the module it with C compiler Import the package in your python code
  • 28. Cython Compiling a module => setuptools print “hello world!” setup.py from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext setup( cmdclass = {'build_ext': build_ext}, ext_modules = [Extension(”hello", [”hello.pyx"])] )
  • 29. Cython cdef extern from "readline/readline.h": char* readline(char*) intadd_history(char*) def readline_loop(): while True: line = readline("c:>”) if not line: break add_history(line)
  • 30. Cython setup.py from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext setup( cmdclass = {'build_ext': build_ext}, ext_modules = [Extension(‘readlineloop’, [‘readline-loop.pyx’], libraries = [‘readline’])] )
  • 31.
  • 34. Thank You! ruda.moura@gmail.com sebastien.tandel@gmail.com