SlideShare a Scribd company logo
1 of 32
Download to read offline
Bind Python and C
C Extensions for Python 3
StarNight @ COSCUP 2015
Who am I?
潘建宏 / Jian-Hong Pan (StarNight)
About Me : http://about.me/StarNight
出沒在~
GitHub : starnight
PTT : zack2004
plurk : StarNight
Facebook : Jian-Hong Pan
目前繼續在種花店當個打雜園丁 ~
Outline
● Standing on the shoulders of giants
● What I want
● Binding flow
● Examples:
○ Without arguments
○ With passed arguments
○ With variables return
● Difference of binding between Python 2 & 3
Stand on the Shoulders of Giants
● Cython - Making Python as Fast as C by
Mosky
● The Future of GUI Programming with Python
by TP
● "My grand scheme was to build a C API for
the web that's what I thought PHP was." by
Rasmus Lerdorf (The father of PHP)
● Many languages make wrappers bind C!
What I Want
● Python is convenient
and good to make
prototype.
● I am familier with C
more. (是個慣C
● Therefore, I write C
with my “right hand”,
and write Python
with my “left hand”.
From 灌籃高手漫畫
What I want (Cont.
● Compiled C program is more efficient than
Python.
● My OS default enviroment is “Python 3”.
● To be convenient to make prototype and to
have efficiency at the same time, I should
make Python 3 call some C libraries written
by myself, not Cython.
● Python 3 with C extensions.
test.py
lib***.h
lib***.c
bind.c
setup.py
C extension
import
module
Binding Flow
Binding Flow (cont.
1. test.py is the usual Python application.
2. The module is composited with lib***.h and
lib***.c.
3. To be imported by Python, the bind.c is the
wrapper of the module.
4. setup.py tells compiler how to build and
output the wrapped C extension module.
5. test.py imports C extension module.
Examples
https://github.com/starnight/python-c-extension
Traditional Chinese Description on StarNight’s Blog
#include <python.h>
To access the internal Python API.
PEP 3121
00-HelloWorld: Without Arguments
● libmypy.h & libmypy.c:
○ Function declaration & Implementation
○ PyObject * hello(PyObject *self)
● bind.c:
○ Define Python Methods: helloworld_funcs
○ Define Python Module: helloworld_mod
○ Initial Module Function: PyInit_helloworld calls
PyModule_Create(&helloworld_mod)
points to the returned object
points to this module object
Define Python Methods
struct PyMethodDef {
const char *ml_name; // name of method
PyCFunction ml_meth; // pointer to the C implementation
int ml_flags; // flag bits
const char *ml_doc; // pointer to the description string
};
typedef struct PyMethodDef PyMethodDef;
PS. flag bits could be:
METH_VARARGS, METH_KEYWORDS,
METH_NOARGS, METH_O
Define Python Module
typedef struct PyModuleDef{
PyModuleDef_Base m_base; // PyModuleDef_HEAD_INIT
const char* m_name; // pointer to the module name
const char* m_doc; // pointer to the module description
Py_ssize_t m_size; // -1 in this example
PyMethodDef *m_methods; // previous PyMethodDef
inquiry m_reload; // should be NULL
traverseproc m_traverse; // could be NULL
inquiry m_clear; // could be NULL
freefunc m_free; // could be NULL
}PyModuleDef;
00-HelloWorld: Without Arguments
● setup.py:
from distutils.core import setup, Extension
setup(
name = "helloworld",
version = "1.0",
ext_modules = [Extension("helloworld",
["bind.c", "libmypy.c"])]
);
00-HelloWorld: Without Arguments
● Makefile:
python setup.py build_ext --inplace
● test.py:
import helloworld
print(helloworld.hello());
help(helloworld);
module name module description
method name
method description
01-HeyMan: With Passed Arguments
● libmypy.h & libmypy.c:
○ Add heyman function
○ PyObject * heyman(PyObject *self, PyObject *args);
○ heyman calls
PyArg_ParseTuple(args, "is", &num, &name)
● bind.c
○ Add heyman to defined Python Methods:
helloworld_funcs
points to passed arguments object
int
character
string
01-HeyMan: With Passed Arguments
● test.py
import helloworld
print(helloworld.hello());
print(helloworld.heyman(5, "StarNight"));
help(helloworld);
02-Add: With Variable Return
● libmypy.h & libmypy.c:
○ Add add function
○ PyObject * add(PyObject *self, PyObject *args);
○ add calls
return Py_BuildValue("is", num1 + num2, eq)
● bind.c
○ Add add to defined Python Methods:
helloworld_funcs
points to the returned object
character
string
int
02-Add: With Variable Return
● test.py
import helloworld
print(helloworld.hello());
print(helloworld.heyman(5, "StarNight"));
print(helloworld.add(5, 6));
help(helloworld);
Recap
1. Include python.h
2. Declare and implement functions you want.
3. Define Python methods’ mapping table with
PyMethodDef structures which wraps the
functions.
4. Define Python module with PyModuleDef
structure which is the namespace of the
methods’ mapping table.
5. Implement the initial function which initials
the module.
03-CrossVersion
● It is the difference of binding between
Python 2 & 3.
● bind.c
○ Python 3 has module definition structure
(PyModuleDef), but Python 2 does not.
○ Python 3’s Initial funciton:
■ PyInit_<module name> calls PyModule_Create
○ Python 2’s Initial funciton:
■ init<module name> calls Py_InitModule3
Module Definition in Python 3
Python 3’s initial function
Python 2’s initial function
Reference
● Python Extension Programming with C
● Extending Python with C or C++
● Migrating C extensions
● Porting Extension Modules to Python 3
● Parsing arguments and building values
Thank you ~

More Related Content

What's hot

Kyrylo Cherneha "C++ & Python Interaction in Automotive Industry"
Kyrylo Cherneha "C++ & Python Interaction in Automotive Industry"Kyrylo Cherneha "C++ & Python Interaction in Automotive Industry"
Kyrylo Cherneha "C++ & Python Interaction in Automotive Industry"LogeekNightUkraine
 
How to deliver a Python project
How to deliver a Python projectHow to deliver a Python project
How to deliver a Python projectmattjdavidson
 
Introduction to Go programming language
Introduction to Go programming languageIntroduction to Go programming language
Introduction to Go programming languageSlawomir Dorzak
 
Dive into Pinkoi 2013
Dive into Pinkoi 2013Dive into Pinkoi 2013
Dive into Pinkoi 2013Mosky Liu
 
Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Robert Stern
 
Beginning python programming
Beginning python programmingBeginning python programming
Beginning python programmingkanteshraj
 
kikstart journey of Golang with Hello world - Gopherlabs
kikstart journey of Golang with Hello world - Gopherlabs kikstart journey of Golang with Hello world - Gopherlabs
kikstart journey of Golang with Hello world - Gopherlabs sangam biradar
 
PyWPS Development restart
PyWPS Development restartPyWPS Development restart
PyWPS Development restartJachym Cepicky
 
Torch7 and ConvNet
Torch7 and ConvNetTorch7 and ConvNet
Torch7 and ConvNetQin Jian
 
Python 如何執行
Python 如何執行Python 如何執行
Python 如何執行kao kuo-tung
 
Briefly Rust - Daniele Esposti - Codemotion Rome 2017
Briefly Rust - Daniele Esposti - Codemotion Rome 2017Briefly Rust - Daniele Esposti - Codemotion Rome 2017
Briefly Rust - Daniele Esposti - Codemotion Rome 2017Codemotion
 
Mobile C++
Mobile C++Mobile C++
Mobile C++gdgut
 

What's hot (20)

Go. Why it goes
Go. Why it goesGo. Why it goes
Go. Why it goes
 
Kyrylo Cherneha "C++ & Python Interaction in Automotive Industry"
Kyrylo Cherneha "C++ & Python Interaction in Automotive Industry"Kyrylo Cherneha "C++ & Python Interaction in Automotive Industry"
Kyrylo Cherneha "C++ & Python Interaction in Automotive Industry"
 
How to deliver a Python project
How to deliver a Python projectHow to deliver a Python project
How to deliver a Python project
 
Introduction to Go programming language
Introduction to Go programming languageIntroduction to Go programming language
Introduction to Go programming language
 
Dive into Pinkoi 2013
Dive into Pinkoi 2013Dive into Pinkoi 2013
Dive into Pinkoi 2013
 
Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1
 
Beginning python programming
Beginning python programmingBeginning python programming
Beginning python programming
 
kikstart journey of Golang with Hello world - Gopherlabs
kikstart journey of Golang with Hello world - Gopherlabs kikstart journey of Golang with Hello world - Gopherlabs
kikstart journey of Golang with Hello world - Gopherlabs
 
Golang preso
Golang presoGolang preso
Golang preso
 
PyWPS Development restart
PyWPS Development restartPyWPS Development restart
PyWPS Development restart
 
Python lecture 02
Python lecture 02Python lecture 02
Python lecture 02
 
Torch7 and ConvNet
Torch7 and ConvNetTorch7 and ConvNet
Torch7 and ConvNet
 
Python on pi
Python on piPython on pi
Python on pi
 
Torch intro
Torch introTorch intro
Torch intro
 
Python 如何執行
Python 如何執行Python 如何執行
Python 如何執行
 
Ruxmon.2013-08.-.CodeBro!
Ruxmon.2013-08.-.CodeBro!Ruxmon.2013-08.-.CodeBro!
Ruxmon.2013-08.-.CodeBro!
 
Briefly Rust - Daniele Esposti - Codemotion Rome 2017
Briefly Rust - Daniele Esposti - Codemotion Rome 2017Briefly Rust - Daniele Esposti - Codemotion Rome 2017
Briefly Rust - Daniele Esposti - Codemotion Rome 2017
 
Software maintenance PyConPL 2016
Software maintenance PyConPL 2016Software maintenance PyConPL 2016
Software maintenance PyConPL 2016
 
Vim and Python
Vim and PythonVim and Python
Vim and Python
 
Mobile C++
Mobile C++Mobile C++
Mobile C++
 

Viewers also liked

Build a Micro HTTP Server for Embedded System
Build a Micro HTTP Server for Embedded SystemBuild a Micro HTTP Server for Embedded System
Build a Micro HTTP Server for Embedded SystemJian-Hong Pan
 
Micro HTTP Server Implemented in C @ COSCUP 2016
Micro HTTP Server Implemented in C @ COSCUP 2016Micro HTTP Server Implemented in C @ COSCUP 2016
Micro HTTP Server Implemented in C @ COSCUP 2016Jian-Hong Pan
 
Learn How to Develop Embedded System for ARM @ 2014.12.22 JuluOSDev
Learn How to Develop Embedded System for ARM @ 2014.12.22 JuluOSDevLearn How to Develop Embedded System for ARM @ 2014.12.22 JuluOSDev
Learn How to Develop Embedded System for ARM @ 2014.12.22 JuluOSDevJian-Hong Pan
 
Find the bottleneck of your system
Find the bottleneck of your systemFind the bottleneck of your system
Find the bottleneck of your systemJian-Hong Pan
 
The Simple Scheduler in Embedded System @ OSDC.TW 2014
The Simple Scheduler in Embedded System @ OSDC.TW 2014The Simple Scheduler in Embedded System @ OSDC.TW 2014
The Simple Scheduler in Embedded System @ OSDC.TW 2014Jian-Hong Pan
 
The Considerations for Internet of Things @ 2017
The Considerations for Internet of Things @ 2017The Considerations for Internet of Things @ 2017
The Considerations for Internet of Things @ 2017Jian-Hong Pan
 

Viewers also liked (6)

Build a Micro HTTP Server for Embedded System
Build a Micro HTTP Server for Embedded SystemBuild a Micro HTTP Server for Embedded System
Build a Micro HTTP Server for Embedded System
 
Micro HTTP Server Implemented in C @ COSCUP 2016
Micro HTTP Server Implemented in C @ COSCUP 2016Micro HTTP Server Implemented in C @ COSCUP 2016
Micro HTTP Server Implemented in C @ COSCUP 2016
 
Learn How to Develop Embedded System for ARM @ 2014.12.22 JuluOSDev
Learn How to Develop Embedded System for ARM @ 2014.12.22 JuluOSDevLearn How to Develop Embedded System for ARM @ 2014.12.22 JuluOSDev
Learn How to Develop Embedded System for ARM @ 2014.12.22 JuluOSDev
 
Find the bottleneck of your system
Find the bottleneck of your systemFind the bottleneck of your system
Find the bottleneck of your system
 
The Simple Scheduler in Embedded System @ OSDC.TW 2014
The Simple Scheduler in Embedded System @ OSDC.TW 2014The Simple Scheduler in Embedded System @ OSDC.TW 2014
The Simple Scheduler in Embedded System @ OSDC.TW 2014
 
The Considerations for Internet of Things @ 2017
The Considerations for Internet of Things @ 2017The Considerations for Internet of Things @ 2017
The Considerations for Internet of Things @ 2017
 

Similar to Bind Python and C @ COSCUP 2015

Boost.Python: C++ and Python Integration
Boost.Python: C++ and Python IntegrationBoost.Python: C++ and Python Integration
Boost.Python: C++ and Python IntegrationGlobalLogic Ukraine
 
[GSoC 2017] gopy: Updating gopy to support Python3 and PyPy
[GSoC 2017] gopy: Updating gopy to support Python3 and PyPy[GSoC 2017] gopy: Updating gopy to support Python3 and PyPy
[GSoC 2017] gopy: Updating gopy to support Python3 and PyPyDong-hee Na
 
Threads and Callbacks for Embedded Python
Threads and Callbacks for Embedded PythonThreads and Callbacks for Embedded Python
Threads and Callbacks for Embedded PythonYi-Lung Tsai
 
Take advantage of C++ from Python
Take advantage of C++ from PythonTake advantage of C++ from Python
Take advantage of C++ from PythonYung-Yu Chen
 
Cluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CCluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CSteffen Wenz
 
CAP444-Unit-3-Polymorphism.pptx
CAP444-Unit-3-Polymorphism.pptxCAP444-Unit-3-Polymorphism.pptx
CAP444-Unit-3-Polymorphism.pptxSurajgroupsvideo
 
PyCon2022 - Building Python Extensions
PyCon2022 - Building Python ExtensionsPyCon2022 - Building Python Extensions
PyCon2022 - Building Python ExtensionsHenry Schreiner
 
What Are Python Modules? Edureka
What Are Python Modules? EdurekaWhat Are Python Modules? Edureka
What Are Python Modules? EdurekaEdureka!
 
Mender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and GolangMender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and GolangMender.io
 
Notes about moving from python to c++ py contw 2020
Notes about moving from python to c++ py contw 2020Notes about moving from python to c++ py contw 2020
Notes about moving from python to c++ py contw 2020Yung-Yu Chen
 
나도 할 수 있다 오픈소스
나도 할 수 있다 오픈소스나도 할 수 있다 오픈소스
나도 할 수 있다 오픈소스효준 강
 
Migrating python.org to buildbot 9 and python 3
Migrating python.org to buildbot 9 and python 3Migrating python.org to buildbot 9 and python 3
Migrating python.org to buildbot 9 and python 3Craig Rodrigues
 
Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016maiktoepfer
 

Similar to Bind Python and C @ COSCUP 2015 (20)

Boost.Python: C++ and Python Integration
Boost.Python: C++ and Python IntegrationBoost.Python: C++ and Python Integration
Boost.Python: C++ and Python Integration
 
[GSoC 2017] gopy: Updating gopy to support Python3 and PyPy
[GSoC 2017] gopy: Updating gopy to support Python3 and PyPy[GSoC 2017] gopy: Updating gopy to support Python3 and PyPy
[GSoC 2017] gopy: Updating gopy to support Python3 and PyPy
 
Threads and Callbacks for Embedded Python
Threads and Callbacks for Embedded PythonThreads and Callbacks for Embedded Python
Threads and Callbacks for Embedded Python
 
Ruby meets Go
Ruby meets GoRuby meets Go
Ruby meets Go
 
Brief Introduction to Cython
Brief Introduction to CythonBrief Introduction to Cython
Brief Introduction to Cython
 
C pythontalk
C pythontalkC pythontalk
C pythontalk
 
Take advantage of C++ from Python
Take advantage of C++ from PythonTake advantage of C++ from Python
Take advantage of C++ from Python
 
Cluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CCluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in 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
 
CAP444-Unit-3-Polymorphism.pptx
CAP444-Unit-3-Polymorphism.pptxCAP444-Unit-3-Polymorphism.pptx
CAP444-Unit-3-Polymorphism.pptx
 
PyCon2022 - Building Python Extensions
PyCon2022 - Building Python ExtensionsPyCon2022 - Building Python Extensions
PyCon2022 - Building Python Extensions
 
What Are Python Modules? Edureka
What Are Python Modules? EdurekaWhat Are Python Modules? Edureka
What Are Python Modules? Edureka
 
Mender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and GolangMender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and Golang
 
Introduction to cython
Introduction to cythonIntroduction to cython
Introduction to cython
 
Notes about moving from python to c++ py contw 2020
Notes about moving from python to c++ py contw 2020Notes about moving from python to c++ py contw 2020
Notes about moving from python to c++ py contw 2020
 
나도 할 수 있다 오픈소스
나도 할 수 있다 오픈소스나도 할 수 있다 오픈소스
나도 할 수 있다 오픈소스
 
Rusty Python
Rusty PythonRusty Python
Rusty Python
 
Pythonpresent
PythonpresentPythonpresent
Pythonpresent
 
Migrating python.org to buildbot 9 and python 3
Migrating python.org to buildbot 9 and python 3Migrating python.org to buildbot 9 and python 3
Migrating python.org to buildbot 9 and python 3
 
Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016
 

More from Jian-Hong Pan

國稅局,我也好想用電腦報稅
國稅局,我也好想用電腦報稅國稅局,我也好想用電腦報稅
國稅局,我也好想用電腦報稅Jian-Hong Pan
 
Share the Experience of Using Embedded Development Board
Share the Experience of Using Embedded Development BoardShare the Experience of Using Embedded Development Board
Share the Experience of Using Embedded Development BoardJian-Hong Pan
 
Package a PyApp as a Flatpak Package: An HTTP Server for Example @ PyCon APAC...
Package a PyApp as a Flatpak Package: An HTTP Server for Example @ PyCon APAC...Package a PyApp as a Flatpak Package: An HTTP Server for Example @ PyCon APAC...
Package a PyApp as a Flatpak Package: An HTTP Server for Example @ PyCon APAC...Jian-Hong Pan
 
Launch the First Process in Linux System
Launch the First Process in Linux SystemLaunch the First Process in Linux System
Launch the First Process in Linux SystemJian-Hong Pan
 
Let's trace Linux Lernel with KGDB @ COSCUP 2021
Let's trace Linux Lernel with KGDB @ COSCUP 2021Let's trace Linux Lernel with KGDB @ COSCUP 2021
Let's trace Linux Lernel with KGDB @ COSCUP 2021Jian-Hong Pan
 
A Journey to Boot Linux on Raspberry Pi
A Journey to Boot Linux on Raspberry PiA Journey to Boot Linux on Raspberry Pi
A Journey to Boot Linux on Raspberry PiJian-Hong Pan
 
Have a Simple Modbus Server
Have a Simple Modbus ServerHave a Simple Modbus Server
Have a Simple Modbus ServerJian-Hong Pan
 
Software Packaging for Cross OS Distribution
Software Packaging for Cross OS DistributionSoftware Packaging for Cross OS Distribution
Software Packaging for Cross OS DistributionJian-Hong Pan
 
Nasa Hackthon 2018 Light Wonder - Go! Polar Bear!
Nasa Hackthon 2018 Light Wonder - Go! Polar Bear!Nasa Hackthon 2018 Light Wonder - Go! Polar Bear!
Nasa Hackthon 2018 Light Wonder - Go! Polar Bear!Jian-Hong Pan
 
LoRaWAN class module and subsystem
LoRaWAN class module and subsystemLoRaWAN class module and subsystem
LoRaWAN class module and subsystemJian-Hong Pan
 
Let's Have an IEEE 802.15.4 over LoRa Linux Device Driver for IoT
Let's Have an IEEE 802.15.4 over LoRa Linux Device Driver for IoTLet's Have an IEEE 802.15.4 over LoRa Linux Device Driver for IoT
Let's Have an IEEE 802.15.4 over LoRa Linux Device Driver for IoTJian-Hong Pan
 
Debug C/C++ Programs More Comfortably @ 2014.12.14 Trace Code Meetup
Debug C/C++ Programs More Comfortably @ 2014.12.14 Trace Code MeetupDebug C/C++ Programs More Comfortably @ 2014.12.14 Trace Code Meetup
Debug C/C++ Programs More Comfortably @ 2014.12.14 Trace Code MeetupJian-Hong Pan
 
Make Your Own Developement Board @ 2014.4.21 JuluOSDev
Make Your Own Developement Board @ 2014.4.21 JuluOSDevMake Your Own Developement Board @ 2014.4.21 JuluOSDev
Make Your Own Developement Board @ 2014.4.21 JuluOSDevJian-Hong Pan
 

More from Jian-Hong Pan (14)

國稅局,我也好想用電腦報稅
國稅局,我也好想用電腦報稅國稅局,我也好想用電腦報稅
國稅局,我也好想用電腦報稅
 
Share the Experience of Using Embedded Development Board
Share the Experience of Using Embedded Development BoardShare the Experience of Using Embedded Development Board
Share the Experience of Using Embedded Development Board
 
Package a PyApp as a Flatpak Package: An HTTP Server for Example @ PyCon APAC...
Package a PyApp as a Flatpak Package: An HTTP Server for Example @ PyCon APAC...Package a PyApp as a Flatpak Package: An HTTP Server for Example @ PyCon APAC...
Package a PyApp as a Flatpak Package: An HTTP Server for Example @ PyCon APAC...
 
Launch the First Process in Linux System
Launch the First Process in Linux SystemLaunch the First Process in Linux System
Launch the First Process in Linux System
 
Let's trace Linux Lernel with KGDB @ COSCUP 2021
Let's trace Linux Lernel with KGDB @ COSCUP 2021Let's trace Linux Lernel with KGDB @ COSCUP 2021
Let's trace Linux Lernel with KGDB @ COSCUP 2021
 
A Journey to Boot Linux on Raspberry Pi
A Journey to Boot Linux on Raspberry PiA Journey to Boot Linux on Raspberry Pi
A Journey to Boot Linux on Raspberry Pi
 
Have a Simple Modbus Server
Have a Simple Modbus ServerHave a Simple Modbus Server
Have a Simple Modbus Server
 
Software Packaging for Cross OS Distribution
Software Packaging for Cross OS DistributionSoftware Packaging for Cross OS Distribution
Software Packaging for Cross OS Distribution
 
Nasa Hackthon 2018 Light Wonder - Go! Polar Bear!
Nasa Hackthon 2018 Light Wonder - Go! Polar Bear!Nasa Hackthon 2018 Light Wonder - Go! Polar Bear!
Nasa Hackthon 2018 Light Wonder - Go! Polar Bear!
 
LoRaWAN class module and subsystem
LoRaWAN class module and subsystemLoRaWAN class module and subsystem
LoRaWAN class module and subsystem
 
Let's Have an IEEE 802.15.4 over LoRa Linux Device Driver for IoT
Let's Have an IEEE 802.15.4 over LoRa Linux Device Driver for IoTLet's Have an IEEE 802.15.4 over LoRa Linux Device Driver for IoT
Let's Have an IEEE 802.15.4 over LoRa Linux Device Driver for IoT
 
Debug C/C++ Programs More Comfortably @ 2014.12.14 Trace Code Meetup
Debug C/C++ Programs More Comfortably @ 2014.12.14 Trace Code MeetupDebug C/C++ Programs More Comfortably @ 2014.12.14 Trace Code Meetup
Debug C/C++ Programs More Comfortably @ 2014.12.14 Trace Code Meetup
 
Make Your Own Developement Board @ 2014.4.21 JuluOSDev
Make Your Own Developement Board @ 2014.4.21 JuluOSDevMake Your Own Developement Board @ 2014.4.21 JuluOSDev
Make Your Own Developement Board @ 2014.4.21 JuluOSDev
 
Node.js 1, 2, 3
Node.js 1, 2, 3Node.js 1, 2, 3
Node.js 1, 2, 3
 

Recently uploaded

Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 

Recently uploaded (20)

Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 

Bind Python and C @ COSCUP 2015

  • 1. Bind Python and C C Extensions for Python 3 StarNight @ COSCUP 2015
  • 2. Who am I? 潘建宏 / Jian-Hong Pan (StarNight) About Me : http://about.me/StarNight 出沒在~ GitHub : starnight PTT : zack2004 plurk : StarNight Facebook : Jian-Hong Pan 目前繼續在種花店當個打雜園丁 ~
  • 3. Outline ● Standing on the shoulders of giants ● What I want ● Binding flow ● Examples: ○ Without arguments ○ With passed arguments ○ With variables return ● Difference of binding between Python 2 & 3
  • 4. Stand on the Shoulders of Giants ● Cython - Making Python as Fast as C by Mosky ● The Future of GUI Programming with Python by TP ● "My grand scheme was to build a C API for the web that's what I thought PHP was." by Rasmus Lerdorf (The father of PHP) ● Many languages make wrappers bind C!
  • 5. What I Want ● Python is convenient and good to make prototype. ● I am familier with C more. (是個慣C ● Therefore, I write C with my “right hand”, and write Python with my “left hand”. From 灌籃高手漫畫
  • 6. What I want (Cont. ● Compiled C program is more efficient than Python. ● My OS default enviroment is “Python 3”. ● To be convenient to make prototype and to have efficiency at the same time, I should make Python 3 call some C libraries written by myself, not Cython. ● Python 3 with C extensions.
  • 8. Binding Flow (cont. 1. test.py is the usual Python application. 2. The module is composited with lib***.h and lib***.c. 3. To be imported by Python, the bind.c is the wrapper of the module. 4. setup.py tells compiler how to build and output the wrapped C extension module. 5. test.py imports C extension module.
  • 10. #include <python.h> To access the internal Python API. PEP 3121
  • 11. 00-HelloWorld: Without Arguments ● libmypy.h & libmypy.c: ○ Function declaration & Implementation ○ PyObject * hello(PyObject *self) ● bind.c: ○ Define Python Methods: helloworld_funcs ○ Define Python Module: helloworld_mod ○ Initial Module Function: PyInit_helloworld calls PyModule_Create(&helloworld_mod) points to the returned object points to this module object
  • 12. Define Python Methods struct PyMethodDef { const char *ml_name; // name of method PyCFunction ml_meth; // pointer to the C implementation int ml_flags; // flag bits const char *ml_doc; // pointer to the description string }; typedef struct PyMethodDef PyMethodDef; PS. flag bits could be: METH_VARARGS, METH_KEYWORDS, METH_NOARGS, METH_O
  • 13.
  • 14. Define Python Module typedef struct PyModuleDef{ PyModuleDef_Base m_base; // PyModuleDef_HEAD_INIT const char* m_name; // pointer to the module name const char* m_doc; // pointer to the module description Py_ssize_t m_size; // -1 in this example PyMethodDef *m_methods; // previous PyMethodDef inquiry m_reload; // should be NULL traverseproc m_traverse; // could be NULL inquiry m_clear; // could be NULL freefunc m_free; // could be NULL }PyModuleDef;
  • 15.
  • 16. 00-HelloWorld: Without Arguments ● setup.py: from distutils.core import setup, Extension setup( name = "helloworld", version = "1.0", ext_modules = [Extension("helloworld", ["bind.c", "libmypy.c"])] );
  • 17. 00-HelloWorld: Without Arguments ● Makefile: python setup.py build_ext --inplace ● test.py: import helloworld print(helloworld.hello()); help(helloworld);
  • 18. module name module description method name method description
  • 19. 01-HeyMan: With Passed Arguments ● libmypy.h & libmypy.c: ○ Add heyman function ○ PyObject * heyman(PyObject *self, PyObject *args); ○ heyman calls PyArg_ParseTuple(args, "is", &num, &name) ● bind.c ○ Add heyman to defined Python Methods: helloworld_funcs points to passed arguments object int character string
  • 20.
  • 21. 01-HeyMan: With Passed Arguments ● test.py import helloworld print(helloworld.hello()); print(helloworld.heyman(5, "StarNight")); help(helloworld);
  • 22.
  • 23. 02-Add: With Variable Return ● libmypy.h & libmypy.c: ○ Add add function ○ PyObject * add(PyObject *self, PyObject *args); ○ add calls return Py_BuildValue("is", num1 + num2, eq) ● bind.c ○ Add add to defined Python Methods: helloworld_funcs points to the returned object character string int
  • 24.
  • 25. 02-Add: With Variable Return ● test.py import helloworld print(helloworld.hello()); print(helloworld.heyman(5, "StarNight")); print(helloworld.add(5, 6)); help(helloworld);
  • 26.
  • 27. Recap 1. Include python.h 2. Declare and implement functions you want. 3. Define Python methods’ mapping table with PyMethodDef structures which wraps the functions. 4. Define Python module with PyModuleDef structure which is the namespace of the methods’ mapping table. 5. Implement the initial function which initials the module.
  • 28. 03-CrossVersion ● It is the difference of binding between Python 2 & 3. ● bind.c ○ Python 3 has module definition structure (PyModuleDef), but Python 2 does not. ○ Python 3’s Initial funciton: ■ PyInit_<module name> calls PyModule_Create ○ Python 2’s Initial funciton: ■ init<module name> calls Py_InitModule3
  • 29. Module Definition in Python 3 Python 3’s initial function Python 2’s initial function
  • 30.
  • 31. Reference ● Python Extension Programming with C ● Extending Python with C or C++ ● Migrating C extensions ● Porting Extension Modules to Python 3 ● Parsing arguments and building values