SlideShare ist ein Scribd-Unternehmen logo
1 von 30
Downloaden Sie, um offline zu lesen
C!

ctypes
extending python was never easier!
Anant Narayanan
Malaviya National Institute of Technology
So what is python?
• Dynamically typed, interpreted
language
prototyping
• Allows for fastinterpreter , thanks to
the awesome

•

The interpreter revolutionized how
programmers attacked problems

• Emphasizes simplicity
Extending Python with ctypes | Anant Narayanan | Gnunify
’07, Pune
How does python
work?
Classic implementation
• C language, also known written in the
as CPython
API to communicate
• Provides “an-Land” and “Python-Land”
between C

•

Standard functions to convert C data
types to python types and vice-versa

Extending Python with ctypes | Anant Narayanan | Gnunify
’07, Pune
Python
Fundamentals
• Simple set of data types
• string, int/long, float and unicode
Every function
• an object , class or data type is
•

These objects are, in reality, wrappers
over corresponding C types

python functions implemented
• Basichigher level functions in python
in C,
itself

Extending Python with ctypes | Anant Narayanan | Gnunify
’07, Pune
C fundamentals
data types
• Rich set ofpointers! , including the
infamous

•
•
•

Basic types: int, char, double, float, w_char_t
Arrays: char*, w_char_t*, int*
Structures and Unions

Extending Python with ctypes | Anant Narayanan | Gnunify
’07, Pune
The need for
bindings
The
• a lotpython standard library provides
of useful functionality

•

However, python’s success is mainly
attributed to the availability of
bindings to many popular libraries

• Gtk+, wxWidgets, openGL, SDL,
cdrecord, Gnome etc...
Extending Python with ctypes | Anant Narayanan | Gnunify
’07, Pune
The “good old” way
•

use functions defined by “Python.h”
to export objects:

•
•
•
•
•

PyObject *obj
PyArg_ParseTuple
Py_BuildValue
Py_INCREF, Py_DECREF
PyModule_AddObject, Py_InitModule

Extending Python with ctypes | Anant Narayanan | Gnunify
’07, Pune
The “good old” way
• Good for simple libraries
• Tends to be very monotonous
pyGTK uses code-generation instead
•
Converts function prototypes found
• in C Header files to scheme-like `def'
files, which are then parsed to
generated Python Module code

Extending Python with ctypes | Anant Narayanan | Gnunify
’07, Pune
SWIG: The Next Step
• Abstracts code-generation
defines function
• Single “interface” filethen converted
prototypes, which is
to appropriate C binding code

only generates code for python
• Not PHP, Perl, Ruby and Java too ,
but

• Used by Subversion and other major
projects
Extending Python with ctypes | Anant Narayanan | Gnunify
’07, Pune
What’s wrong with
SWIG?

•

Need to learn the swig “interface”
language

• Produces computer-generated code
•
•

Ugly to read!
Impossible to debug!

• Additional dependency and build
routine
Extending Python with ctypes | Anant Narayanan | Gnunify
’07, Pune
Enter ctypes!
An even higher layer of abstraction

•
Code generation done at memory
• level
Allows dynamic execution of
• functions in a shared library

• .dll, .so and .dylib supported
Extending Python with ctypes | Anant Narayanan | Gnunify
’07, Pune
What does this
mean?
extend python with functions from C

• libraries - easy bindings written in
pure python

•

write your callback functions in
python and call them from C

•

use python as a true “glue” language:
interconnecting several libraries to
create large, coherent programs

Extending Python with ctypes | Anant Narayanan | Gnunify
’07, Pune
How does it work?
import
ctypes
import your library
prepare
parameters
call the (next)
function
Extending Python with ctypes | Anant Narayanan | Gnunify
’07, Pune
Searching for
libraries
•

ctypes.util.find_library

•
•
•

Runs `ldconfig `, `gcc` and `objdump`
Returns filename of the library
OS X: Standard paths are looked in; absolute
path of dylib returned

Extending Python with ctypes | Anant Narayanan | Gnunify
’07, Pune
Importing libraries
• ctypes.CDLL (nam e, m ode, handle)
•
•

Represents a loaded shared library

•

Functions are assumed to return int

Functions in these libraries are called using the
standard calling convention of C

ctypes.PyDLL (nam e, m ode, handle)

•
•

Python GIL is not released, hence exceptions are
caught and returned. Useful for using the python
C API itself!

Extending Python with ctypes | Anant Narayanan | Gnunify
’07, Pune
Importing libraries
•

preset library loaders available (just
call cdll)

• Or manually load with LibraryLoader
and LoadLibrary

instance
• pythonapi represents anAPI loadedof
PyDLL with the CPython

• Also available:

windll, oledll

Extending Python with ctypes | Anant Narayanan | Gnunify
’07, Pune
Accessing functions
•

All functions are exported as
attributes of the CDLL/PyDLL class

Functions
• _FuncPtr are objects of type

•

Called just like regular python
callables

• But remember to first convert the
parameters!
Extending Python with ctypes | Anant Narayanan | Gnunify
’07, Pune
Type conversion
• int/ long, None, strings and unicode
objects are automatically converted
for you!

•

any types other than these must first
be converted using the data types
provided by ctypes

• python type
data type

ctype

Extending Python with ctypes | Anant Narayanan | Gnunify
’07, Pune

C
•
•

Some common
ctypes
Mutable
• c_char, c_wchar, c_byte, c_ubyte
• c_short, c_ushort
• c_int, c_uint, c_long, c_ulong, c_float, c_double
Immutable
•

c_char_p, c_wchar_p, c_void_p

Extending Python with ctypes | Anant Narayanan | Gnunify
’07, Pune
Mutability for
strings
•

st = “Hello World!”
nt = c_char_p(st)
print nt
# returns c_char_p(“Hello World!”)
nt.value = “Bye Bye World!”
print nt
# returns c_char_p(“Bye Bye World!”)
print st
# returns “Hello World!”

•

Use
•
•

create_string_buffer(< bytes> )
create_string_buffer(< string> )

Extending Python with ctypes | Anant Narayanan | Gnunify
’07, Pune
Specifying
parameter types
Set the argtypes
• function object attribute for the

• This attribute is a sequence of ctypes:
•

• myfunc.argtypes = [c_char_p, c_int, c_double]
Setting this attribute will ensure that
function is called with the correct
number and types of attributes, and
will also convert where possible

Extending Python with ctypes | Anant Narayanan | Gnunify
’07, Pune
Specifying return
types
Set the restype
• function object attribute for the
This
• validattribute corresponds to any
ctype

•

Also possible to set it as a python
callable if the actual return type is an
integer

In this case,
will be
• invoked withthe callableresult; and the
the actual

Extending Python with ctypes | Anant Narayanan | Gnunify
’07, Pune

result of the callable will appear to be
Using Pointers
• Use the quick and easy byref function
• Or construct a proper pointer ctype
be accessed
• Value canattribute, and by the
contents
also by
offset

you don
• Use byref whenlater on 't need the
pointer object
Extending Python with ctypes | Anant Narayanan | Gnunify
’07, Pune
Structures & Unions
structures are defined
• Allthe structure base classas children
of

•

The _fields_ attribute is a list of 2tuples, containing a field name and a
field type

•

The field name is any valid python
identifier and the field type is any
valid ctype.

Extending Python with ctypes | Anant Narayanan | Gnunify
’07, Pune
Structures & Unions
•

Similarly Unions are extended from
the union base class

Both are
• instance initialized by creating an
of the class

•

Bit fields are also possible
bit-length
• Pass the of each listof the field as the
3 tuple
in the _fields_
rd

attribute

Extending Python with ctypes | Anant Narayanan | Gnunify
’07, Pune
Forward
declarations
The _fields_ attribute
• elements that haven't can't contain
been declared

•

However, you can always define or
add to the _fields_ attribute later!

Be careful
• before youof using your structure
have finalized your
_fields_, this could lead to
inconsistencies

Extending Python with ctypes | Anant Narayanan | Gnunify
’07, Pune
Arrays
Simply multiply the base
• with a positive integer! element type
•

myArray = (c_int * 5)(, 2, 3, 4, 5)
for i in range(5):
print myArray[i]

and object that represent
• ...Or create and instantiate it
your array

•

Arrays are proper ctypes, so you can
include them in your structures and
other complex types

Extending Python with ctypes | Anant Narayanan | Gnunify
’07, Pune
Typecasting
•

ctypes will automatically accept arrays
of a base type, where it was expecting
just the base type

• In all other cases: strict type checking!
cast function to typecast one
• Use theanother
type to
•

obj = (c_byte * 10)()
castedObj = cast(obj, POINTER(c_int))

Extending Python with ctypes | Anant Narayanan | Gnunify
’07, Pune
Callbacks
of the
• Function pointers arebe created by
CFUNCTYPE and can
instantiating that class

• The result type is the first argument,
followed by the arguments that your
callback function must expect

Connect the function pointer to the
actual python callback by
instantiating the object returned by
CFUNCTYPE
Extending Python with ctypes | Anant Narayanan | Gnunify

’07, Pune

•
What now?
•

Clearly, wrapping libraries in ctypes is
far easier, and more maintainable

• Not much performance loss (code
generation at runtime)

Extending Python with ctypes | Anant Narayanan | Gnunify
’07, Pune

Weitere ähnliche Inhalte

Was ist angesagt?

Presentation on python
Presentation on pythonPresentation on python
Presentation on pythonwilliam john
 
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYAChapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYAMaulik Borsaniya
 
Ground Gurus - Python Code Camp - Day 3 - Classes
Ground Gurus - Python Code Camp - Day 3 - ClassesGround Gurus - Python Code Camp - Day 3 - Classes
Ground Gurus - Python Code Camp - Day 3 - ClassesChariza Pladin
 
Python Introduction | JNTUA | R19 | UNIT 1
Python Introduction | JNTUA | R19 | UNIT 1 Python Introduction | JNTUA | R19 | UNIT 1
Python Introduction | JNTUA | R19 | UNIT 1 FabMinds
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming LanguageTahani Al-Manie
 
introduction of python in data science
introduction of python in data scienceintroduction of python in data science
introduction of python in data sciencebhavesh lande
 
Introduction to python for Beginners
Introduction to python for Beginners Introduction to python for Beginners
Introduction to python for Beginners Sujith Kumar
 
What is Python? An overview of Python for science.
What is Python? An overview of Python for science.What is Python? An overview of Python for science.
What is Python? An overview of Python for science.Nicholas Pringle
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonYi-Fan Chu
 
Python quick guide1
Python quick guide1Python quick guide1
Python quick guide1Kanchilug
 
An Introduction to Python Programming
An Introduction to Python ProgrammingAn Introduction to Python Programming
An Introduction to Python ProgrammingMorteza Zakeri
 
علم البيانات - Data Sience
علم البيانات - Data Sience علم البيانات - Data Sience
علم البيانات - Data Sience App Ttrainers .com
 
Python - Introduction
Python - IntroductionPython - Introduction
Python - Introductionstn_tkiller
 

Was ist angesagt? (19)

Python Tutorial Part 2
Python Tutorial Part 2Python Tutorial Part 2
Python Tutorial Part 2
 
Python basics
Python basicsPython basics
Python basics
 
Presentation on python
Presentation on pythonPresentation on python
Presentation on python
 
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYAChapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
 
Ground Gurus - Python Code Camp - Day 3 - Classes
Ground Gurus - Python Code Camp - Day 3 - ClassesGround Gurus - Python Code Camp - Day 3 - Classes
Ground Gurus - Python Code Camp - Day 3 - Classes
 
Python programming
Python programmingPython programming
Python programming
 
Python Introduction | JNTUA | R19 | UNIT 1
Python Introduction | JNTUA | R19 | UNIT 1 Python Introduction | JNTUA | R19 | UNIT 1
Python Introduction | JNTUA | R19 | UNIT 1
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
 
introduction of python in data science
introduction of python in data scienceintroduction of python in data science
introduction of python in data science
 
Introduction to python for Beginners
Introduction to python for Beginners Introduction to python for Beginners
Introduction to python for Beginners
 
Python training
Python trainingPython training
Python training
 
What is Python? An overview of Python for science.
What is Python? An overview of Python for science.What is Python? An overview of Python for science.
What is Python? An overview of Python for science.
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Python quick guide1
Python quick guide1Python quick guide1
Python quick guide1
 
Python final ppt
Python final pptPython final ppt
Python final ppt
 
Python
PythonPython
Python
 
An Introduction to Python Programming
An Introduction to Python ProgrammingAn Introduction to Python Programming
An Introduction to Python Programming
 
علم البيانات - Data Sience
علم البيانات - Data Sience علم البيانات - Data Sience
علم البيانات - Data Sience
 
Python - Introduction
Python - IntroductionPython - Introduction
Python - Introduction
 

Ähnlich wie Extending Python with ctypes

C Types - Extending Python
C Types - Extending PythonC Types - Extending Python
C Types - Extending PythonPriyank Kapadia
 
Introduction to Python Programing
Introduction to Python ProgramingIntroduction to Python Programing
Introduction to Python Programingsameer patil
 
Programming with Python: Week 1
Programming with Python: Week 1Programming with Python: Week 1
Programming with Python: Week 1Ahmet Bulut
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh MalothBhavsingh Maloth
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programmingChetan Giridhar
 
Introduction to Python – Learn Python Programming.pptx
Introduction to Python – Learn Python Programming.pptxIntroduction to Python – Learn Python Programming.pptx
Introduction to Python – Learn Python Programming.pptxHassanShah396906
 
What is Python?
What is Python?What is Python?
What is Python?PranavSB
 
Paython courses in pune ppt
Paython courses in pune pptPaython courses in pune ppt
Paython courses in pune pptsambhajimeher
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonMohammed Rafi
 
Python for katana
Python for katanaPython for katana
Python for katanakedar nath
 
Python for security professionals by katoh jeremiah [py con ng 2018]
Python for security professionals by katoh jeremiah [py con ng 2018]Python for security professionals by katoh jeremiah [py con ng 2018]
Python for security professionals by katoh jeremiah [py con ng 2018]jerrykatoh
 

Ähnlich wie Extending Python with ctypes (20)

C Types - Extending Python
C Types - Extending PythonC Types - Extending Python
C Types - Extending Python
 
Introduction to Python Programing
Introduction to Python ProgramingIntroduction to Python Programing
Introduction to Python Programing
 
Introduction_to_Python.pptx
Introduction_to_Python.pptxIntroduction_to_Python.pptx
Introduction_to_Python.pptx
 
Programming with Python: Week 1
Programming with Python: Week 1Programming with Python: Week 1
Programming with Python: Week 1
 
Python for ML.pptx
Python for ML.pptxPython for ML.pptx
Python for ML.pptx
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
Python intro
Python introPython intro
Python intro
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
 
Python
PythonPython
Python
 
Python Module-1.1.pdf
Python Module-1.1.pdfPython Module-1.1.pdf
Python Module-1.1.pdf
 
Introduction to Python – Learn Python Programming.pptx
Introduction to Python – Learn Python Programming.pptxIntroduction to Python – Learn Python Programming.pptx
Introduction to Python – Learn Python Programming.pptx
 
Python Demo.pptx
Python Demo.pptxPython Demo.pptx
Python Demo.pptx
 
Numba
NumbaNumba
Numba
 
Python Demo.pptx
Python Demo.pptxPython Demo.pptx
Python Demo.pptx
 
What is Python?
What is Python?What is Python?
What is Python?
 
Class_X_PYTHON_J.pdf
Class_X_PYTHON_J.pdfClass_X_PYTHON_J.pdf
Class_X_PYTHON_J.pdf
 
Paython courses in pune ppt
Paython courses in pune pptPaython courses in pune ppt
Paython courses in pune ppt
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Python for katana
Python for katanaPython for katana
Python for katana
 
Python for security professionals by katoh jeremiah [py con ng 2018]
Python for security professionals by katoh jeremiah [py con ng 2018]Python for security professionals by katoh jeremiah [py con ng 2018]
Python for security professionals by katoh jeremiah [py con ng 2018]
 

Mehr von Anant Narayanan

Enterprise Scale Knowledge Graphs
Enterprise Scale Knowledge GraphsEnterprise Scale Knowledge Graphs
Enterprise Scale Knowledge GraphsAnant Narayanan
 
Building an Intelligent Assistant
Building an Intelligent AssistantBuilding an Intelligent Assistant
Building an Intelligent AssistantAnant Narayanan
 
WebRTC: A Practical Introduction
WebRTC: A Practical IntroductionWebRTC: A Practical Introduction
WebRTC: A Practical IntroductionAnant Narayanan
 
Message Passing vs. Data Synchronization
Message Passing vs. Data SynchronizationMessage Passing vs. Data Synchronization
Message Passing vs. Data SynchronizationAnant Narayanan
 
Firebase: Tales from the Trenches
Firebase: Tales from the TrenchesFirebase: Tales from the Trenches
Firebase: Tales from the TrenchesAnant Narayanan
 
Error Handling in WebRTC
Error Handling in WebRTCError Handling in WebRTC
Error Handling in WebRTCAnant Narayanan
 
WebRTC: User Security & Privacy
WebRTC: User Security & PrivacyWebRTC: User Security & Privacy
WebRTC: User Security & PrivacyAnant Narayanan
 
Firefox Architecture Overview
Firefox Architecture OverviewFirefox Architecture Overview
Firefox Architecture OverviewAnant Narayanan
 
Next Generation Browser Add-Ons
Next Generation Browser Add-OnsNext Generation Browser Add-Ons
Next Generation Browser Add-OnsAnant Narayanan
 
An Overview of Distributed Debugging
An Overview of Distributed DebuggingAn Overview of Distributed Debugging
An Overview of Distributed DebuggingAnant Narayanan
 
A Brief Incursion into Botnet Detection
A Brief Incursion into Botnet DetectionA Brief Incursion into Botnet Detection
A Brief Incursion into Botnet DetectionAnant Narayanan
 
Mozilla Weave: Integrating Services into the Browser
Mozilla Weave: Integrating Services into the BrowserMozilla Weave: Integrating Services into the Browser
Mozilla Weave: Integrating Services into the BrowserAnant Narayanan
 
Distributed File Systems: An Overview
Distributed File Systems: An OverviewDistributed File Systems: An Overview
Distributed File Systems: An OverviewAnant Narayanan
 
Innovating with Mozilla Labs
Innovating with Mozilla LabsInnovating with Mozilla Labs
Innovating with Mozilla LabsAnant Narayanan
 
Glendix: The Why and the How
Glendix: The Why and the HowGlendix: The Why and the How
Glendix: The Why and the HowAnant Narayanan
 

Mehr von Anant Narayanan (20)

Enterprise Scale Knowledge Graphs
Enterprise Scale Knowledge GraphsEnterprise Scale Knowledge Graphs
Enterprise Scale Knowledge Graphs
 
Building an Intelligent Assistant
Building an Intelligent AssistantBuilding an Intelligent Assistant
Building an Intelligent Assistant
 
WebRTC: A Practical Introduction
WebRTC: A Practical IntroductionWebRTC: A Practical Introduction
WebRTC: A Practical Introduction
 
Message Passing vs. Data Synchronization
Message Passing vs. Data SynchronizationMessage Passing vs. Data Synchronization
Message Passing vs. Data Synchronization
 
Firebase: Tales from the Trenches
Firebase: Tales from the TrenchesFirebase: Tales from the Trenches
Firebase: Tales from the Trenches
 
WebRTC: An Overview
WebRTC: An OverviewWebRTC: An Overview
WebRTC: An Overview
 
Error Handling in WebRTC
Error Handling in WebRTCError Handling in WebRTC
Error Handling in WebRTC
 
WebRTC Demystified
WebRTC DemystifiedWebRTC Demystified
WebRTC Demystified
 
WebRTC: User Security & Privacy
WebRTC: User Security & PrivacyWebRTC: User Security & Privacy
WebRTC: User Security & Privacy
 
Firefox Architecture Overview
Firefox Architecture OverviewFirefox Architecture Overview
Firefox Architecture Overview
 
πP
πPπP
πP
 
Next Generation Browser Add-Ons
Next Generation Browser Add-OnsNext Generation Browser Add-Ons
Next Generation Browser Add-Ons
 
An Overview of Distributed Debugging
An Overview of Distributed DebuggingAn Overview of Distributed Debugging
An Overview of Distributed Debugging
 
A Brief Incursion into Botnet Detection
A Brief Incursion into Botnet DetectionA Brief Incursion into Botnet Detection
A Brief Incursion into Botnet Detection
 
Mozilla Weave: Integrating Services into the Browser
Mozilla Weave: Integrating Services into the BrowserMozilla Weave: Integrating Services into the Browser
Mozilla Weave: Integrating Services into the Browser
 
about:labs
about:labsabout:labs
about:labs
 
Distributed File Systems: An Overview
Distributed File Systems: An OverviewDistributed File Systems: An Overview
Distributed File Systems: An Overview
 
Innovating with Mozilla Labs
Innovating with Mozilla LabsInnovating with Mozilla Labs
Innovating with Mozilla Labs
 
Glendix: The Why and the How
Glendix: The Why and the HowGlendix: The Why and the How
Glendix: The Why and the How
 
Mozilla Prism
Mozilla PrismMozilla Prism
Mozilla Prism
 

Kürzlich hochgeladen

The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 

Kürzlich hochgeladen (20)

The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 

Extending Python with ctypes

  • 1. C! ctypes extending python was never easier! Anant Narayanan Malaviya National Institute of Technology
  • 2. So what is python? • Dynamically typed, interpreted language prototyping • Allows for fastinterpreter , thanks to the awesome • The interpreter revolutionized how programmers attacked problems • Emphasizes simplicity Extending Python with ctypes | Anant Narayanan | Gnunify ’07, Pune
  • 3. How does python work? Classic implementation • C language, also known written in the as CPython API to communicate • Provides “an-Land” and “Python-Land” between C • Standard functions to convert C data types to python types and vice-versa Extending Python with ctypes | Anant Narayanan | Gnunify ’07, Pune
  • 4. Python Fundamentals • Simple set of data types • string, int/long, float and unicode Every function • an object , class or data type is • These objects are, in reality, wrappers over corresponding C types python functions implemented • Basichigher level functions in python in C, itself Extending Python with ctypes | Anant Narayanan | Gnunify ’07, Pune
  • 5. C fundamentals data types • Rich set ofpointers! , including the infamous • • • Basic types: int, char, double, float, w_char_t Arrays: char*, w_char_t*, int* Structures and Unions Extending Python with ctypes | Anant Narayanan | Gnunify ’07, Pune
  • 6. The need for bindings The • a lotpython standard library provides of useful functionality • However, python’s success is mainly attributed to the availability of bindings to many popular libraries • Gtk+, wxWidgets, openGL, SDL, cdrecord, Gnome etc... Extending Python with ctypes | Anant Narayanan | Gnunify ’07, Pune
  • 7. The “good old” way • use functions defined by “Python.h” to export objects: • • • • • PyObject *obj PyArg_ParseTuple Py_BuildValue Py_INCREF, Py_DECREF PyModule_AddObject, Py_InitModule Extending Python with ctypes | Anant Narayanan | Gnunify ’07, Pune
  • 8. The “good old” way • Good for simple libraries • Tends to be very monotonous pyGTK uses code-generation instead • Converts function prototypes found • in C Header files to scheme-like `def' files, which are then parsed to generated Python Module code Extending Python with ctypes | Anant Narayanan | Gnunify ’07, Pune
  • 9. SWIG: The Next Step • Abstracts code-generation defines function • Single “interface” filethen converted prototypes, which is to appropriate C binding code only generates code for python • Not PHP, Perl, Ruby and Java too , but • Used by Subversion and other major projects Extending Python with ctypes | Anant Narayanan | Gnunify ’07, Pune
  • 10. What’s wrong with SWIG? • Need to learn the swig “interface” language • Produces computer-generated code • • Ugly to read! Impossible to debug! • Additional dependency and build routine Extending Python with ctypes | Anant Narayanan | Gnunify ’07, Pune
  • 11. Enter ctypes! An even higher layer of abstraction • Code generation done at memory • level Allows dynamic execution of • functions in a shared library • .dll, .so and .dylib supported Extending Python with ctypes | Anant Narayanan | Gnunify ’07, Pune
  • 12. What does this mean? extend python with functions from C • libraries - easy bindings written in pure python • write your callback functions in python and call them from C • use python as a true “glue” language: interconnecting several libraries to create large, coherent programs Extending Python with ctypes | Anant Narayanan | Gnunify ’07, Pune
  • 13. How does it work? import ctypes import your library prepare parameters call the (next) function Extending Python with ctypes | Anant Narayanan | Gnunify ’07, Pune
  • 14. Searching for libraries • ctypes.util.find_library • • • Runs `ldconfig `, `gcc` and `objdump` Returns filename of the library OS X: Standard paths are looked in; absolute path of dylib returned Extending Python with ctypes | Anant Narayanan | Gnunify ’07, Pune
  • 15. Importing libraries • ctypes.CDLL (nam e, m ode, handle) • • Represents a loaded shared library • Functions are assumed to return int Functions in these libraries are called using the standard calling convention of C ctypes.PyDLL (nam e, m ode, handle) • • Python GIL is not released, hence exceptions are caught and returned. Useful for using the python C API itself! Extending Python with ctypes | Anant Narayanan | Gnunify ’07, Pune
  • 16. Importing libraries • preset library loaders available (just call cdll) • Or manually load with LibraryLoader and LoadLibrary instance • pythonapi represents anAPI loadedof PyDLL with the CPython • Also available: windll, oledll Extending Python with ctypes | Anant Narayanan | Gnunify ’07, Pune
  • 17. Accessing functions • All functions are exported as attributes of the CDLL/PyDLL class Functions • _FuncPtr are objects of type • Called just like regular python callables • But remember to first convert the parameters! Extending Python with ctypes | Anant Narayanan | Gnunify ’07, Pune
  • 18. Type conversion • int/ long, None, strings and unicode objects are automatically converted for you! • any types other than these must first be converted using the data types provided by ctypes • python type data type ctype Extending Python with ctypes | Anant Narayanan | Gnunify ’07, Pune C
  • 19. • • Some common ctypes Mutable • c_char, c_wchar, c_byte, c_ubyte • c_short, c_ushort • c_int, c_uint, c_long, c_ulong, c_float, c_double Immutable • c_char_p, c_wchar_p, c_void_p Extending Python with ctypes | Anant Narayanan | Gnunify ’07, Pune
  • 20. Mutability for strings • st = “Hello World!” nt = c_char_p(st) print nt # returns c_char_p(“Hello World!”) nt.value = “Bye Bye World!” print nt # returns c_char_p(“Bye Bye World!”) print st # returns “Hello World!” • Use • • create_string_buffer(< bytes> ) create_string_buffer(< string> ) Extending Python with ctypes | Anant Narayanan | Gnunify ’07, Pune
  • 21. Specifying parameter types Set the argtypes • function object attribute for the • This attribute is a sequence of ctypes: • • myfunc.argtypes = [c_char_p, c_int, c_double] Setting this attribute will ensure that function is called with the correct number and types of attributes, and will also convert where possible Extending Python with ctypes | Anant Narayanan | Gnunify ’07, Pune
  • 22. Specifying return types Set the restype • function object attribute for the This • validattribute corresponds to any ctype • Also possible to set it as a python callable if the actual return type is an integer In this case, will be • invoked withthe callableresult; and the the actual Extending Python with ctypes | Anant Narayanan | Gnunify ’07, Pune result of the callable will appear to be
  • 23. Using Pointers • Use the quick and easy byref function • Or construct a proper pointer ctype be accessed • Value canattribute, and by the contents also by offset you don • Use byref whenlater on 't need the pointer object Extending Python with ctypes | Anant Narayanan | Gnunify ’07, Pune
  • 24. Structures & Unions structures are defined • Allthe structure base classas children of • The _fields_ attribute is a list of 2tuples, containing a field name and a field type • The field name is any valid python identifier and the field type is any valid ctype. Extending Python with ctypes | Anant Narayanan | Gnunify ’07, Pune
  • 25. Structures & Unions • Similarly Unions are extended from the union base class Both are • instance initialized by creating an of the class • Bit fields are also possible bit-length • Pass the of each listof the field as the 3 tuple in the _fields_ rd attribute Extending Python with ctypes | Anant Narayanan | Gnunify ’07, Pune
  • 26. Forward declarations The _fields_ attribute • elements that haven't can't contain been declared • However, you can always define or add to the _fields_ attribute later! Be careful • before youof using your structure have finalized your _fields_, this could lead to inconsistencies Extending Python with ctypes | Anant Narayanan | Gnunify ’07, Pune
  • 27. Arrays Simply multiply the base • with a positive integer! element type • myArray = (c_int * 5)(, 2, 3, 4, 5) for i in range(5): print myArray[i] and object that represent • ...Or create and instantiate it your array • Arrays are proper ctypes, so you can include them in your structures and other complex types Extending Python with ctypes | Anant Narayanan | Gnunify ’07, Pune
  • 28. Typecasting • ctypes will automatically accept arrays of a base type, where it was expecting just the base type • In all other cases: strict type checking! cast function to typecast one • Use theanother type to • obj = (c_byte * 10)() castedObj = cast(obj, POINTER(c_int)) Extending Python with ctypes | Anant Narayanan | Gnunify ’07, Pune
  • 29. Callbacks of the • Function pointers arebe created by CFUNCTYPE and can instantiating that class • The result type is the first argument, followed by the arguments that your callback function must expect Connect the function pointer to the actual python callback by instantiating the object returned by CFUNCTYPE Extending Python with ctypes | Anant Narayanan | Gnunify ’07, Pune •
  • 30. What now? • Clearly, wrapping libraries in ctypes is far easier, and more maintainable • Not much performance loss (code generation at runtime) Extending Python with ctypes | Anant Narayanan | Gnunify ’07, Pune