How to attach a C method to existing Python class?

We are currently coding of python C methods are being used. The base of all the libraries such as Numpy, Opencv, pytorch etc are built with the C and C++ i.e. these libraries internally call the Compiled C code where code will be executed in the machine and the result will be return in python wrapper.

Why are we using the C methods in python?

The reason why we are using the C method in python is the performance. The python performance will be decreased because of the dynamic typing.

  • It has to reduce the type of operands to be passed, before the interpreter executes an operation. These type of operations hits the execution time of the program.

  • The C Modules allow us to check these operands and directly execute the machine code through the python.

  • To work with the c module, we have to link it with the python. There are different ways to link c module with the python.

  • One of the way is by using the CPython API. To understand the working and usage of the Cpython API. The procedure for using this API is as follows.

Procedure to use C API in python

Following are the steps to use C API in Python −

Firstly, we have to install the package of python3-dev to work with the c methods in python. The following code is to be used to install the package.

pip install cpython

After using that code, we have to create a directory named extension and in that directory we have to create a file with the extension.c. Let’s say the file is greet.c, now in this file include the following described headers.

#include <python.h>
#include <string.h>

The Cpython library will provide the python.h header and also provides us extension functions and types. This library helps us to integrate the python and c.


Now, let’s create a program to work with the cpython library. The following is the code that we can use for working with the cpython library.

static PyObject* name(PyObject *self, PyObject* args){
   char *name;
   char greeting[255] = "Hello ";
   if (!PyArg_ParseTuple(args, "s", &name)){
      return NULL;
   strcat(greeting, name);
   return Py_BuildValue("s", greeting);

In the above code we used the pyobject. The pyobject is the python instance represented in C. This pyobject function has two arguments self and args.

  • self indicates the present object/module

  • args used to indicate the python arguments.

Defining our C method

The PyArg_ParseTuple is passed in python and is used to interpret the c values. The s in the second argument is a string value. If it is any other type it will throw the type error in python. The py_buildvalue works opposite to the PyArg_ParseTuple. That means it interprets the values in python from c.

After defining our C method, we have to interface it with the python. The following code is used to interpret with the python.

static PyMethodDef moduleMethods[] = {
   {"name", name, METH_VARARGS, "Greets with your name"}

Now, after interfacing our C method with the python we have to define the module type. The below code can be used to define the module type.

static struct PyModuleDef greetModule = {
   "Greetings Module",
PyMODINIT_FUNC PyInit_greet(void){
   return PyModule_Create(&greetModule);

Importing the method in the current program

Now, after defining the method type and creating the method we have to import that in our python environment.

import greet
print("Name: ", greet.__name__)
print("Docstring: ", greet.__doc__)
print("Greeting: ","Lezwon"))

If we execute the above code will get an error nomodulefound. This is because the module is not lined with the python yet. So the following setup to be done to use the created module with the c language in python.


First we have to install setup tools in our python environment. The following code has to be used.

pip install setuptools

Now, we have to create the setup file with the python extension. The following code is to be used in that python file.

from setuptools import setup, Extension
ext_modules = [
   Extension('greet', sources = ['greetmodule.c']),
   name = 'Greeting Project',
   ext_modules = ext_modules

In the above code we used the greet. This represents the module that we created in c. For compiling our code, we have to use the following command.

python build_ext --inplace

Now we can run the below.

import greet
print("Name: ", greet.__name__)
print("Docstring: ", greet.__doc__)
print("Greeting: ","Lezwon"))

Updated on: 15-May-2023


Kickstart Your Career

Get certified by completing the course

Get Started