Using C in Python was never this Easy
Use your C functions in Python or any other Programming Langauge.
You might be thinking, there are a lot of blogs on the internet on how to use C in Python. This is gonna be different, just follow along đ.
We are going to utilize the .dll format to communicate between C and Python. DLL stands for dynamic link library. If you were ever into gaming, I bet you have come across this format at some point in your life.
âERROR: The application cannot start because the XYZ.dll file was missing. Re-Installing the appâŚâ
Haha! Now letâs see what and how are we going to proceed with the blog.
- Write a Script in C and Execute
- Install Scons in Python
- Make the C code compatible with export functions to the DLL file.
- Run the functions with Python using our DLL file.
Letâs Write a simple Script to add two numbers in C
We will be using two files â âexample.câ and âexample.hâ. We will write two functions:
- Find if the number is a Prime or Composite number
- Find if the number is odd or even
Now letâs dive into the code:
example. h
#ifndef EXAMPLE_H#define EXAMPLE_H
#include <stdio.h>int prime(int n);int odd_even(int n);
#endif
example.c
#include "example.h"int prime(int n) { int i; for (i = 2; i < n; i++) { if (n % i == 0) { return 0; }
} return 1;}
int odd_even(int n) { if (n % 2 == 0) { return 0; } return 1;}
Install Scons using PIP
We are going to use SConstruct for building our C program.
pip install scons
Create a new file â âSConstructâ in the same directory and write
SharedLibrary("output", "example.c")
Save the file and Go to Terminal and write:
scons
This create a DLL file â âoutput.dllâ but we cannot use the C functions yet.
Make C compatible with DLL Export
Now, letâs make the C functions useable from dll file. We need to add â__declspec(dllexport)â before function declaration in example.h.
example.h
#ifndef EXAMPLE_H#define EXAMPLE_H
#include <stdio.h>__declspec(dllexport) int prime(int n);__declspec(dllexport) int odd_even(int n);
#endif
Again go to the terminal and type âsconsâ. This will now build a new âoutput.dllâ. Now letâs test our C functions in Python.
Run DLL files on Python
We create a new âtest.pyâ in the same directory.
test.py
import ctypes
dll = ctypes.CDLL("./output.dll")
print("Output of Prime(9):", dll.prime(9))print("Output of Prime(13):", dll.prime(13))print("Output of odd_even(17):", dll.odd_even(17))print("Output of odd_even(8):", dll.odd_even(8))
Output:
Hoorayyyy! We are successful in our mission!
Why should we use DLL files?
- Itâs an independent file. You can paste the file anywhere and it will be usable.
- The code behind the DLL file remains hidden from the end user.
- Itâs independent of any major Python code modification.
- DLL Files are very light weight
- DLL is one of the standard files on Windows.
I hope you like this Blog.
Github Link â https://github.com/ayushmankumar7/C_in_Python