C Extension Module using Python Last Updated : 27 Mar, 2019 Comments Improve Suggest changes Like Article Like Report Writing a simple C extension module directly using Python’s extension API and no other tools. It is straightforward to make a handcrafted extension module for a simple C code. But first, we have to make sure that the C code has a proper header file. Code #1 : C #include <math.h> extern int gcd(int, int); extern int in_mandel(double x0, double y0, int n); extern int divide(int a, int b, int *remainder); extern double avg(double *a, int n); typedef struct Point { double x, y; } Point; extern double distance(Point *p1, Point *p2); The header would correspond to a library that has been separately compiled. The code below illustrates the basics of writing extension functions, following this assumption. Code #2: CPP 1== # include "Python.h" # include "sample.h" /* int gcd(int, int) */ static PyObject * py_gcd(PyObject * self, PyObject * args) { int x, y, result; if (! PyArg_ParseTuple(args, "ii", &x, &y)) { return NULL; } result = gcd(x, y); return Py_BuildValue("i", result); } /* int divide(int, int, int *) */ static PyObject * py_divide(PyObject * self, PyObject * args) { int a, b, quotient, remainder; if (! PyArg_ParseTuple(args, "ii", &a, &b)) { return NULL; } quotient = divide(a, b, &remainder); return Py_BuildValue("(ii)", quotient, remainder); } Code #3 : Module method table and structure CPP 1== /* Module method table */ static PyMethodDef SampleMethods[] = { {"gcd", py_gcd, METH_VARARGS, "Greatest common divisor"}, {"divide", py_divide, METH_VARARGS, "Integer division"}, { NULL, NULL, 0, NULL} }; /* Module structure */ static struct PyModuleDef samplemodule = { PyModuleDef_HEAD_INIT, "sample", /* name of module */ "A sample module", /* Doc string (may be NULL) */ -1, /* Size of per-interpreter state or -1 */ SampleMethods /* Method table */ }; /* Module initialization function */ PyMODINIT_FUNC PyInit_sample(void) { return PyModule_Create(&samplemodule); } Code #4: Creating a setup.py python file for building the extension module. Python3 # setup.py from distutils.core import setup, Extension setup(name='sample', ext_modules=[ Extension('sample', ['pysample.c'], include_dirs = ['/some/dir'], define_macros = [('FOO','1')], undef_macros = ['BAR'], library_dirs = ['/usr/local/lib'], libraries = ['sample'] ) ] ) Code #5: Now simply use python3 buildlib.py build_ext --inplace, to build the resulting library. bash% python3 setup.py build_ext --inplace running build_ext building 'sample' extension gcc -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/usr/local/include/python3.3m -c pysample.c -o build/temp.macosx-10.6-x86_64-3.3/pysample.o gcc -bundle -undefined dynamic_lookup build/temp.macosx-10.6-x86_64-3.3/pysample.o \ -L/usr/local/lib -lsample -o sample.so bash % The above code will create a shared library called sample.so. Code #6 : Python3 import sample print ("gcd = ", sample.gcd(35, 42)) print ("\ndistance : ", sample.divide(42, 8)) Output : gcd = 7 distance = (5, 2) “Extending and Embedding the Python Interpreter” is a Python's documentation that can be consulted before attempting any kind of handwritten extension. In extension modules, functions can be written as shown in code snippet below. Code #4 : Python3 static PyObject *py_func(PyObject *self, PyObject *args) { ... } PyObject - C data type that represents any Python object. At a very high level, an extension function is a C function that receives a tuple of Python objects (in PyObject *args) and returns a new Python object as a result. The self argument to the function is unused for simple extension functions, but comes into play should you want to define new classes or object types in C. The PyArg_ParseTuple() function is used to convert values from Python to a C representation. As input, it takes a format string that indicates the required values, such as “i” for integer and “d” for double, as well as the addresses of C variables in which to place the converted results. Py_BuildValue() function is used to create Python objects from C data types. It also accepts a format code to indicate the desired type. In the extension functions, it is used to return results back to Python. One feature of Py_BuildValue() is that it can build more complicated kinds of objects, such as tuples and dictionaries. Comment More infoAdvertise with us Next Article C Extension Module using Python M manikachandna97 Follow Improve Article Tags : Python Python-ctype Practice Tags : python Similar Reads External Modules in Python Python is one of the most popular programming languages because of its vast collection of modules which make the work of developers easy and save time from writing the code for a particular task for their program. Python provides various types of modules which include built-in modules and external m 5 min read C API from Extension Module in Python | Set 2 Prerequisite: C API from Extension Module in Python | Set 1 Let's see an example of a new extension module that loads and uses these API functions that we build up in the previous article. Code #1 : C #include "pythonsample.h" /* An extension function that uses the exported API */ static P 2 min read C API from Extension Module in Python | Set 1 Suppose given a C extension module that internally defines a variety of useful functions that can be exported as a public C API for use elsewhere. Now if we want to use these functions inside other extension modules. Then, it is important to know how to link them together but doing it with the C com 3 min read OS Module in Python with Examples The OS module in Python provides functions for interacting with the operating system. OS comes under Python's standard utility modules. This module provides a portable way of using operating system-dependent functionality.The *os* and *os.path* modules include many functions to interact with the fil 10 min read How to create modules in Python 3 ? Modules are simply python code having functions, classes, variables. Any python file with .py extension can be referenced as a module. Although there are some modules available through the python standard library which are installed through python installation, Other modules can be installed using t 4 min read Using Pointers in Python using ctypes In this article, we are going to learn about using pointers in Python using ctypes module. We will see how we can use Pointers in Python programming language using the ctypes module. Some basic operations like storing addresses, pointing to a different variable using pointers, etc. will be demonstra 10 min read Create and Import modules in Python In Python, a module is a self-contained Python file that contains Python statements and definitions, like a file named GFG.py, can be considered as a module named GFG which can be imported with the help of import statement. However, one might get confused about the difference between modules and pac 3 min read Python Module Index Python has a vast ecosystem of modules and packages. These modules enable developers to perform a wide range of tasks without taking the headache of creating a custom module for them to perform a particular task. Whether we have to perform data analysis, set up a web server, or automate tasks, there 4 min read Using C codes in Python | Set 1 Prerequisite: How to Call a C function in Python Let's discuss the problem of accessing C code from Python. As it is very evident that many of Pythonâs built-in libraries are written in C. So, to access C is a very important part of making Python talk to existing libraries. There is an extensive C p 4 min read Using C codes in Python | Set 2 Prerequisite: Using C codes in Python | Set 1 In the previous article, we have discussed how to access C code in Python. Now, let's see how to access C functions. Code #1 : Accessing C functions with Python Python3 1== import work print ("GCD : ", work.gcd(35, 42)) print ("\ndivide : 2 min read Like