Tutorial

Calling C Functions from Python

Published on August 3, 2022
Default avatar

By Pankaj

Calling C Functions from Python

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

We can call a C function from Python program using the ctypes module.

Calling C Function from Python

It involves the following steps:

  1. Creating a C file (.c extension) with the required functions
  2. Creating a shared library file (.so extension) using the C compiler.
  3. In the Python program, create a ctypes.CDLL instance from the shared file.
  4. Finally, call the C function using the format {CDLL_instance}.{function_name}({function_parameters}).

Step 1: Creating a C File with some functions

#include <stdio.h>

int square(int i) {
	return i * i;
}

We have a simple C function that will return the square of an integer. I have saved this function code in the file named my_functions.c.

Step 2: Creating the Shared Library File

We can use the following command to create the shared library file from the C source file.

$ cc -fPIC -shared -o my_functions.so my_functions.c
C File Shared Library File
C File and Shared Library File

Step 3: Calling C Function from Python Program

>>> from ctypes import *
>>> so_file = "/Users/pankaj/my_functions.so"
>>> my_functions = CDLL(so_file)
>>> 
>>> print(type(my_functions))
<class 'ctypes.CDLL'>
>>> 
>>> print(my_functions.square(10))
100
>>> print(my_functions.square(8))
64
>>> 
Calling C Function From Python
Calling C Function From Python

If you change the C program file, you will have to regenerate the shared library file.

Conclusion

The python default implementation is written in C programming and it’s called CPython. So it’s not very uncommon to use C functions in a python program. In this tutorial, we learned how to easily call C functions in a python program.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
December 22, 2021

It does not work properly. Give rise to certain errors.

- shah sawood

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    September 24, 2021

    I found this helpfull. Thankyou very much

    - Adanech Alemu

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      September 9, 2021

      What if my C file includes some other custom C library? It seems that the resulting .so file doesn’t include them.

      - Mauro

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        July 2, 2021

        This was very helpful, thank you a lot, my guy!

        - Itachi Uchiha

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          March 1, 2021

          it doesnt return the intteger that I defined in C file, It does net get a value by using scanf in C program.d

          - Armagan

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            February 13, 2021

            doesn’t work. Traceback (most recent call last): File “”, line 1, in TypeError: ‘LibraryLoader’ object is not callable

            - m j

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              July 22, 2020

              is it possible to connect EM-18 RFID Reader to raspberry pi direct without using RS232 USB adapter? Help me please Sir.

              - Jean Baptiste

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                January 7, 2020

                how can i run cmake commands using python. Eg: I have a folder with .c files in it and they are linked using CMakeList.txt I do compile them using “cmake -H. -Bbuild” commands I need to put the above command in python script and run the .py directly to build the c files.can anyone help me

                - Keerthana

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  December 27, 2019

                  Hi Pankaj, Is it possible to call functions in Linux c executable (not . so file) from python?

                  - Manomugdha Biswas

                    Try DigitalOcean for free

                    Click below to sign up and get $200 of credit to try our products over 60 days!

                    Sign up

                    Join the Tech Talk
                    Success! Thank you! Please check your email for further details.

                    Please complete your information!

                    Get our biweekly newsletter

                    Sign up for Infrastructure as a Newsletter.

                    Hollie's Hub for Good

                    Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

                    Become a contributor

                    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                    Welcome to the developer cloud

                    DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

                    Learn more
                    DigitalOcean Cloud Control Panel