Python C API overview References:

Slides:



Advertisements
Similar presentations
R4 Dynamically loading processes. Overview R4 is closely related to R3, much of what you have written for R3 applies to R4 In R3, we executed procedures.
Advertisements

CS 450 Module R4. R4 Overview Due on March 11 th along with R3. R4 is a small yet critical part of the MPX system. In this module, you will add the functionality.
CSE 303 Lecture 16 Multi-file (larger) programs
A Crash Course Python. Python? Isn’t that a snake? Yes, but it is also a...
CS 106 Introduction to Computer Science I 12 / 04 / 2006 Instructor: Michael Eckmann.
C For Java Programmers Tom Roeder CS sp. Why C? The language of low-level systems programming  Commonly used (legacy code)  Trades off safety.
Tutorial 6 & 7 Symbol Table
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
CMSC 341 Introduction to Java Based on tutorial by Rebecca Hasti at
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
(…A FEW OF THEM) C++ DESIGN PATTERNS. WHAT ARE THEY? Commonly occurring constructs Could be part of good software engineering Not universally agreed Good.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Extending Python with C (Part I – the Basics) June 2002 Brian Quinlan
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
9 Chapter Nine Compiled Web Server Programs. 9 Chapter Objectives Learn about Common Gateway Interface (CGI) Create CGI programs that generate dynamic.
By Noorez Kassam Welcome to JNI. Why use JNI ? 1. You already have significantly large and tricky code written in another language and you would rather.
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
SCRIPTING II/III References:
February 11, 2005 More Pointers Dynamic Memory Allocation.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
Saves memory and reduces swapping No recompilation on changes A DLL can provide after-market support Programs written in different languages can call the.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Testing and Debugging Version 1.0. All kinds of things can go wrong when you are developing a program. The compiler discovers syntax errors in your code.
Lecture 11 Dynamic link libraries. Differences between static libraries and DLLs In static library code is added to the executable. In DLL, the code is.
Pointers review Let a variable aa be defined as ‘int *aa;’, what is stored in aa? Let a variable aa be defined as ‘int ** aa;’ what is stored in aa? Why.
CRT State Stuff Dana Robinson The HDF Group. In the next slide, I show a single executable linked to three dlls. Two dlls and the executable were built.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 4 Pointers and Dynamic Arrays Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
Dynamic memory allocation and Pointers Lecture 4.
Sadegh Aliakbary Sharif University of Technology Spring 2011.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Writing a Run Time DLL The application loads the DLL using LoadLibrary() or LoadLibraryEx(). The standard search sequence is used by the operating system.
Week 2. Functions: int max3(int num1, int num2, int num3) {int result; result = max(max(num1,num2),num3); return result; } //max3.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
Python Let’s get started!.
POINTERS Introduction to Systems Programming - COMP 1002, 1402.
Chapter 5 Linked List by Before you learn Linked List 3 rd level of Data Structures Intermediate Level of Understanding for C++ Please.
Lecture 01a: C++ review Topics: Setting up projects, main program Memory Diagrams Variables / Types (some of) the many-types-of-const's Input / Output.
12. MODULES Rocky K. C. Chang November 6, 2015 (Based on from Charles Dierbach. Introduction to Computer Science Using Python and William F. Punch and.
Today… Modularity, or Writing Functions. Winter 2016CISC101 - Prof. McLeod1.
Python C API overview References:
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Quiz 1 A sample quiz 1 is linked to the grading page on the course web site. Everything up to and including this Friday’s lecture except that conditionals.
Pyragen A PYTHON WRAPPER GENERATOR TO APPLICATION CORE LIBRARIES Fernando PEREIRA, Christian THEIS - HSE/RP EDMS tech note:
T. Meyer ROD Software Workshop July 2002 Scripting and Interpreted Languages Tom Meyer Iowa State University
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
SCRIPTING II & III (LAB 21 AND [OPTIONAL] LAB 22) References:
EXTENDING PYTHON SCRIPTING I/III References:
C++ LANGUAGE MULTIPLE CHOICE QUESTION SET-3
Computer Organization and Design Pointers, Arrays and Strings in C
Lua Extending References:
CSC 253 Lecture 8.
Object Oriented Programming COP3330 / CGS5409
CSC 253 Lecture 8.
Topics Introduction to File Input and Output
Introduction to Java part 2
Variables Title slide variables.
Rocky K. C. Chang 15 November 2018 (Based on Dierbach)
Reference semantics, variables and names
Python Modules.
Topics Introduction to File Input and Output
SPL – PS2 C++ Memory Handling.
Presentation transcript:

Python C API overview References:

Two uses of the Python/C API 1.Extending – Write a dll (.pyd), which exports an initialization function a list of "things" in the module – classes – functions – variables – You can import this just like any (pure) python module – Use the c types / functions in your program import mymodule mymodule.fun(4.1) # A c-function – Many python modules are built this way math pygame numpy …

Two uses of the Python/C API 2.Embedding – Create a python interpreter inside a C program (executable) – Can execute python code Usually from a file Possibly from strings hard-coded, generated by the program. – Need to convert to/from python types – Usually interacts with other C/C++ constructs in the executable.

The Python / C API A ton of functions. Used in both extensions and embedding. Where are they? – Prototypes (.h) c:\pythonXY\include – Code (.lib) c:\pythonXY\libs\python32.lib – Dll (.dll) c:\pythonXY\DLLs\python3.dll Only necessary if embedding Debug vs. Release – The pre-built (windows) binary only include Release builds – If you want Debug dll's and.lib's you have to build from source.

API Naming convention PyXXX_YYY – (Python) class XXX, functionYYY – e.g. PyTuple_Size(…) Py_ZZZ – Global function ZZZ – e.g. Py_Compile(…)

PyObject's Literally everything in Python is a PyObject* – Int ref-count (more on this shortly) – A type structure – Any other data e.g. for tuples, they have a length attribute. The python interpreter owns all objects – The user just has references to them – The first time it is referenced, python malloc's it. – When the refcnt reaches 0, it eventually gets free'd – In (normal) python this is done for us… – …but in the C API we have to manage it.

RefCounting Take a simple example def foo(a): return a[0] ** 2 + a[1] ** 2 x = [3, 2] y = [foo(x), 3.2] z = y z = None Line 1 – 2 creates a new function object. Line 3 creates a new list x. Line 4 calls foo. o a and x refer to the same list (refcnt is 2) o Creates another float (13.0) and returns it o a goes out of scope – the refcnt on the list is now 1 o The 13.0 and 3.2 are part of a new list object (refcnt = 1) Line 5 makes a second reference to the list (Refcnt = 2) Line 6 decreases the refcnt on the list.

RefCounting, cont. …In the C API, you have to manually do it. – Memory Leaks (if you forget to decrement a ref-count) – Invalid memory access (if you forget to increment, and then the object is destroyed) Three functions Py_INCREF(PyObject*); Py_DECREF(PyObject*); Py_XDECREF(PyObject*); // Like previous, but has a NULL- check

When to modify Ref-cnts Look in the C/API documentation – New Reference e.g. PyLong_FromLong(long v) You own a ref-count to it. Make sure to call Py_DECREF when done. – Borrowed Reference e.g. PyList_GetItem(PyObject * list, Py_ssize_t index) Someone else holds a reference Don't call DECREF (unless you called INCREF on it) – Stolen Reference e.g. PyTuple_SetItem(PyObject * tuple, Py_ssize_t index, PyObject * item); You usually have created the PyObject item and own a reference to it. After calling the above func, the tuple stole your reference to item, so don't call DECREF on it.

Converting / Creating variables Integers – C => Python PyObject * PyLong_FromLong(int i); A new reference – make sure you DECREF it! – Python => C int PyLong_AsLong(PyObject*); float PyLong_AsDouble(PyObject*); … – Determining if a PyObject is a (python) int int PyLong_Check(PyObject*); // 1 if it is, 0 if not

Converting / Creating variables, cont. Floats – C => Python PyObject * PyFloat_FromDouble(double d); A new reference – make sure you DECREF it! – Python => C double PyFloat_AsDouble(PyObject*); – Determining if a PyObject* is a (python) float int PyFloat_Check(PyObject*); // 1 if it is.

Converting / Creating variables, cont. Strings – A bit more complicated because python 3.x uses unicode internally, not ANSI (char*) strings. – C => Python PyObject * PyUnicode_FromString(char * s); A new reference – make sure you DECREF it! – Python => C char temps[256]; // PObj is the object (in python) we want to convert PyObject * pBytesObj = PyUnicode_AsUTF8String(pObj); if (pBytesObj) { strcpy(temps, PyBytes_AsString(pBytesObj)); Py_DECREF(pBytesObj); } – Determining if a PyObject* is a (python) unicode object. int PyUnicode_Check(PyObject*); // 1 if it is.

Tuples Determining if a PyObject is a tuple int PyTuple_Check(PyObject*); // 1 if it is. Creating a new tuple PyObject * PyTuple_New(Py_ssize_t len); – Inserting objects into a new tuple PyTuple_SetItem( PyObject * tup, Py_ssize_t index, PyObject * item ); – Note: this steals a reference to item Getting the size of a tuple Py_ssize_t PyTuple_Size(PyObject * tup); Getting an element of a tuple PyOBject * PyTuple_GetItem(PyOBject * tup, Py_ssize_t indx); – Note: this borrows a reference to the item (i.e. the tuple still owns a reference, so don't DECREF if)

Raising exceptions Something happened in your C++ code and you want to raise a python exception If this is in a method / function, you usually return NULL. It is also a good idea to raise an exception so the (python) user can see what happened. PyErr_SetString(PyExc_ValueError, "You did … wrong."); There a bunch of other PyExc_XYZ objects

Handling Exceptions Often a (python API) function fails. – It returns NULL (not helpful) – If usually also sets an exception (helpful) To retrieve the error: void PyErr_Fetch(PyObject ** pType, PyObject ** pValue, PyOBject ** pTraceback); – Note: You need to pass the address of a PyOBject* (use the ampersand) – this function will fill them in. To convert pValue (the error string) to a C-string, use: PyObject * PyObject_Str(myPValue); // New ref – Then convert this (unicode) object to a char * as before.

C/C++ extensions IDLE (or other python interpreter) Python code (.py) C/C++ extension (a.pyd file). Can contain: Python interfaces to C "classes" Python interfaces to C functions Python interfaces to C variables

Creating a C extension (pyd) Goal: – A new class (written in C) – A new function (written in C) – A variable (written in C) – Access all 3 in python Example.py file (myCMod is a C extension): import myCMod C = myCMod.myClass("Bob") print(C.name) # Bob print(C.timestamp) # 0 C.incTimestamp() print(C.timestamp) # 1 print(myCMod.fact(5)) # 120 print(myCMod.aVariable) # Surprise!

Making an extension (pyd) 0. Set up a project – A Win32 console dll (empty) – Put all your code in a single.cpp file – Change output to xyz.pyd (actually a.dll) – Only do a release build (debug can only be run by a debug build of python) – Include includes / libs paths – Link with python32.lib Reference:

Making an extension (pyd) 1.Create a C-type ("guts" of a python object) 2.Create methods for the new type – static PyObject * asdfasdf(…) 3.Create an attribute (PyMemberDef) and method (PyMethodDef) structure for the new type 4.Create a "dictionary" (static PyTypeObject) of functions and attributes for the new type 5.Create a C function in the module (factorial) – I'll let you experiment with this 6.Create a C variable in the module – I'll let you experiment with this too… 7.Make a PyModuleDef to package the module 8.Make a "main" function PyMODINIT_FUNC PyInit_mycmod(void) – Note: in place of mycmod, put the name of the pyd file (exactly)

Embedding the Interpreter C/C++ Program (.exe) Python DLL Python Interpreter Python code (strings) Python (.py) files Other C/C++ objects

Creating the embedded interpreter First, Add any internal C modules – These look just as they did for an extension We aren't building a.dll – they exist solely within the executable Includes: – Define any C classes with Python interfaces – Defining the C methods (return values of PyObject *) – Defining the PyMethodDef structure for the class – Define the PyMethodDef for any stand-alone functions – Define the PyModuleDef structure.

Creating the embedded interpreter "Import" the C module into the embedded interpreter: PyImport_AppendInittab(char * modName, PyObject * (*funcPtr)(void)); The second parameter is a function pointer Pass the address of a function created as in the last step of making an extension. – This function creates an returns a (Python) module object – Possibly also adds classes to this module (if applicable) The function should have a prototype of PyObject * PyInit_myMod(void)

Creating the embedded interpreter Second, start up the interpreter Py_Initialize() – Note: this interpreter will (only) have modules defined with PyImport_AppendInittab. – To add other modules…??? Third, run the rest of the program – At appropriate times, load and run.py files into the embedded interpreter (more on this shortly) Finally, shut down the interpreter Py_Finalize()

Loading / Executing a.py file Load the file into a char * buffer – FILE* of fstream and new / delete Compile the buffer into a code module PyObject * Py_CompileString(char * buff, char * fname, Py_file_input) Import and Execute the code module PyImport_ExecCodeModule(char * name, PyObject * codeMod); – This will run the python code. – If that code references the C functions / classes with Python interfaces, that code will now be run. This will usually interact with the rest of the C structures in the program