SlideShare a Scribd company logo
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
Bind Python and C @ COSCUP 2015
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;
Bind Python and C @ COSCUP 2015
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
Bind Python and C @ COSCUP 2015
01-HeyMan: With Passed Arguments
● test.py
import helloworld
print(helloworld.hello());
print(helloworld.heyman(5, "StarNight"));
help(helloworld);
Bind Python and C @ COSCUP 2015
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
Bind Python and C @ COSCUP 2015
02-Add: With Variable Return
● test.py
import helloworld
print(helloworld.hello());
print(helloworld.heyman(5, "StarNight"));
print(helloworld.add(5, 6));
help(helloworld);
Bind Python and C @ COSCUP 2015
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
Bind Python and C @ COSCUP 2015
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

PDF
Infecting Python Bytecode
PDF
10 reasons to be excited about go
PDF
Writing a Python C extension
PDF
AnyEvent and Plack
PDF
Decision making - for loop , nested loop ,if-else statements , switch in goph...
PDF
PyCon Poland 2016: Maintaining a high load Python project: typical mistakes
PDF
Open source projects with python
PDF
Austin Python Meetup 2017: What's New in Pythons 3.5 and 3.6?
Infecting Python Bytecode
10 reasons to be excited about go
Writing a Python C extension
AnyEvent and Plack
Decision making - for loop , nested loop ,if-else statements , switch in goph...
PyCon Poland 2016: Maintaining a high load Python project: typical mistakes
Open source projects with python
Austin Python Meetup 2017: What's New in Pythons 3.5 and 3.6?

What's hot (20)

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

Viewers also liked (6)

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

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

PPTX
Mixing C++ & Python II: Pybind11
PDF
Interfacing C++ with Python to boost your legacy apps with Python interfaces
PPTX
Python Bindings Overview
PDF
Extending Python - EuroPython 2014
PDF
PyHEP 2018: Tools to bind to Python
PPTX
C pythontalk
ODP
C Types - Extending Python
PDF
Notes about moving from python to c++ py contw 2020
PDF
Cython - close to metal Python
PPTX
Ctypes
PDF
An (Inaccurate) Introduction to Python
PDF
Pybind11 - SciPy 2021
PDF
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
PDF
Extending Python with ctypes
PDF
Porting to Python 3
PDF
PyCon2022 - Building Python Extensions
PDF
Cluj.py Meetup: Extending Python in C
PPTX
Kostiantyn Grygoriev "Wrapping C++ for Python"
ODP
Python 3000
PDF
2 × 3 = 6
Mixing C++ & Python II: Pybind11
Interfacing C++ with Python to boost your legacy apps with Python interfaces
Python Bindings Overview
Extending Python - EuroPython 2014
PyHEP 2018: Tools to bind to Python
C pythontalk
C Types - Extending Python
Notes about moving from python to c++ py contw 2020
Cython - close to metal Python
Ctypes
An (Inaccurate) Introduction to Python
Pybind11 - SciPy 2021
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Extending Python with ctypes
Porting to Python 3
PyCon2022 - Building Python Extensions
Cluj.py Meetup: Extending Python in C
Kostiantyn Grygoriev "Wrapping C++ for Python"
Python 3000
2 × 3 = 6

More from Jian-Hong Pan (16)

PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
D-Bus Usage and Debug Introduction @ COSCUP 2024
PDF
國稅局,我也好想用電腦報稅
PDF
Share the Experience of Using Embedded Development Board
PDF
Package a PyApp as a Flatpak Package: An HTTP Server for Example @ PyCon APAC...
PDF
Launch the First Process in Linux System
PDF
Let's trace Linux Lernel with KGDB @ COSCUP 2021
PDF
A Journey to Boot Linux on Raspberry Pi
PDF
Have a Simple Modbus Server
PDF
Software Packaging for Cross OS Distribution
PDF
Nasa Hackthon 2018 Light Wonder - Go! Polar Bear!
PDF
LoRaWAN class module and subsystem
PDF
Let's Have an IEEE 802.15.4 over LoRa Linux Device Driver for IoT
PDF
Debug C/C++ Programs More Comfortably @ 2014.12.14 Trace Code Meetup
PDF
Make Your Own Developement Board @ 2014.4.21 JuluOSDev
PDF
Node.js 1, 2, 3
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
D-Bus Usage and Debug Introduction @ COSCUP 2024
國稅局,我也好想用電腦報稅
Share the Experience of Using Embedded Development Board
Package a PyApp as a Flatpak Package: An HTTP Server for Example @ PyCon APAC...
Launch the First Process in Linux System
Let's trace Linux Lernel with KGDB @ COSCUP 2021
A Journey to Boot Linux on Raspberry Pi
Have a Simple Modbus Server
Software Packaging for Cross OS Distribution
Nasa Hackthon 2018 Light Wonder - Go! Polar Bear!
LoRaWAN class module and subsystem
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
Make Your Own Developement Board @ 2014.4.21 JuluOSDev
Node.js 1, 2, 3

Recently uploaded (20)

PPTX
CHAPTER 2 - PM Management and IT Context
PDF
AutoCAD Professional Crack 2025 With License Key
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
Nekopoi APK 2025 free lastest update
PDF
CCleaner Pro 6.38.11537 Crack Final Latest Version 2025
PPTX
Transform Your Business with a Software ERP System
PDF
17 Powerful Integrations Your Next-Gen MLM Software Needs
PPTX
assetexplorer- product-overview - presentation
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
Cost to Outsource Software Development in 2025
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
DOCX
Greta — No-Code AI for Building Full-Stack Web & Mobile Apps
PDF
Tally Prime Crack Download New Version 5.1 [2025] (License Key Free
PDF
Salesforce Agentforce AI Implementation.pdf
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
CHAPTER 2 - PM Management and IT Context
AutoCAD Professional Crack 2025 With License Key
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Wondershare Filmora 15 Crack With Activation Key [2025
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Odoo Companies in India – Driving Business Transformation.pdf
Design an Analysis of Algorithms II-SECS-1021-03
Nekopoi APK 2025 free lastest update
CCleaner Pro 6.38.11537 Crack Final Latest Version 2025
Transform Your Business with a Software ERP System
17 Powerful Integrations Your Next-Gen MLM Software Needs
assetexplorer- product-overview - presentation
wealthsignaloriginal-com-DS-text-... (1).pdf
Cost to Outsource Software Development in 2025
How to Choose the Right IT Partner for Your Business in Malaysia
Greta — No-Code AI for Building Full-Stack Web & Mobile Apps
Tally Prime Crack Download New Version 5.1 [2025] (License Key Free
Salesforce Agentforce AI Implementation.pdf
Adobe Illustrator 28.6 Crack My Vision of Vector Design

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
  • 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;
  • 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
  • 21. 01-HeyMan: With Passed Arguments ● test.py import helloworld print(helloworld.hello()); print(helloworld.heyman(5, "StarNight")); help(helloworld);
  • 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
  • 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);
  • 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
  • 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