How to Use C Functions in Python

How to Use C Functions in Python

How to Use C Functions in Python. Have you ever came across the situation where you have to call C function using python? This article is going to help you on very basic level and if you have not. Did you know you can write functions in C and then call them directly from Python? Isn't that cool? Let's skip all the background and the "why would I ever need to do this" for now and just dive on in to the code!

Did you know you can write functions in C and then call them directly from Python? Isn't that cool? Let's skip all the background and the "why would I ever need to do this" for now and just dive on in to the code!

First, the C Function

To demonstrate, we're going to write a program in C to find the factorial of a number. If you don't remember factorials from high school, here's an example:

4! (read four factorial) = 4 * 3 * 2 * 1

That is what our C program is going to do. Fire up a text editor and lets crank this function out:

long factorial(int user_input) {
  long return_val = 1;
  if (user_input <= 0) {
    return -1;
  else {
    for (long i = 1; i <= user_input; i++) {
      return_val *= i;
    }
  }
  return return_val;
}

int main() {
  return 0;
}

We are defining a function called "factorial" which will return a "long." We're using long instead of int because factorial functions can return some pretty big numbers.

Next, we're declaring and initializing return_val which we'll use to return the value of the calculation.

Now, the if statement is ensuring the number passed in by the user is positive, and if not, to return the value of -1. We're returning -1 because later, when we wrap this function in Python, we're going to know that getting -1 back from the C function probably means there was bad input.

If the number returned is greater than 0, we enter our loop in which we use an iterator, i, and multiply our return_val variable by it until i is equal to the number passed in by the user. Basically, this loop is saying:

n! = 1 * 2 * 3 * 4 ... * n

The final part, with the int main() is to appease the C compiler when we turn this into a .so file. I may be mistaken, but I'm pretty sure this part is necessary even though it doesn't do anything. If anyone knows any better, please feel free to mention so.

The Pre-Python Part

Now that our C is written we have a couple things to do before we write the Python bit. First, save the .c file. I called mine cfactorial.c. Now, we have to turn this into a "shared object" file. In Linux, the command to do so is this:

$ cc -fPIC -shared -o cfactorial.so cfactorial.c

This particular command will make a cfactorial.so out of my cfactorial.c file. Now, to the actual Python

The Python Part

Almost done! Fire up that text editor again and lets script out some Python. First, we need to import the ctypes module. Then, if you're anything like me, you'll want to put the absolute path of the .so file into its own variable. So the top of my pyfactorial.py looks like this:

from ctypes import *

so_file = '/home/ewhiting/cstuff/cfactorial.so'

The next thing we want to do is create our cdll object out of our previously created .so file. So, after the so_file variable assignment, put:

cfactorial = CDLL(so_file)

Now, technically at this point you can start messing with calling the C function in the Python script by running python in the command line but lets be a little responsible first. Before we play with it some more, lets wrap our C function in a Python function. After creating the cfactorial variable, create the following function:

def factorial(num):
  c_return = cfactorial.factorial(num)
  if (c_return != -1):
    return c_return
  else:
    return "C Function failed, check inputs"

Save this file as pyfactorial.py. Altogether, it should look like this:

from ctypes import *

so_file = '/home/ewhiting/cstuff/cfactorial.so'
cfactorial = CDLL(so_file)

def factorial(num):
  c_return = cfactorial.factorial(num)
  if (c_return != -1):
    return c_return
  else:
    return "C Function failed, check inputs"

Note, the way to call functions inside the imported C shared object file is by saying <CDLL Object>.<function name from C code>(<parameter>). Easy!

So basically, any time we want to use that C function within Python, we call the factorial function which will run the C function with the parameter passed in by the user and evaluate the result. If the C function returns -1 (remember we put that in there), the Python script knows that there was a problem. Otherwise, it will return the number. Lets try it out! Fire up your terminal and start python

>>> import pyfactorial as pf
>>> pf.factorial(5)
120
>>> pf.factorial(10)
3628800
>>> pf.factorial(-4)
'C Function failed, check inputs'

Ta-da!! That's the basic idea behind using C functions in Python. This is definitely a tool worth having. Apply all your other programmerly knowledge to making awesome functions and features, and let me know if you have any questions.

*** ***===================================================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

Complete Python Bootcamp: Go from zero to hero in Python 3

Python for Time Series Data Analysis

C Programming For Beginners - Master the C Language

Advanced C Programming: Pointers

C Programming For Beginners

Python Programming For Beginners From Scratch

Python Network Programming | Network Apps & Hacking Tools

Intro To SQLite Databases for Python Programming

Ethical Hacking With Python, JavaScript and Kali Linux

Beginner’s guide on Python: Learn python from scratch! (New)

Python for Beginners: Complete Python Programming

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

Hire Now: https://bit.ly/394wdOx

Mobile App Development Company India | Ecommerce Web Development Company India

Mobile App Development Company India | Ecommerce Web Development Company India

Best Mobile App Development Company India, WebClues Global is one of the leading web and mobile app development company. Our team offers complete IT solutions including Cross-Platform App Development, CMS & E-Commerce, and UI/UX Design.

We are custom eCommerce Development Company working with all types of industry verticals and providing them end-to-end solutions for their eCommerce store development.

Know more about Top E-Commerce Web Development Company

Python Tutorial - Learn Python for Machine Learning and Web Development

Python Tutorial - Learn Python for Machine Learning and Web Development

Python tutorial for beginners - Learn Python for Machine Learning and Web Development. Can Python be used for machine learning? Python is widely considered as the preferred language for teaching and learning ML (Machine Learning). Can I use Python for web development? Python can be used to build server-side web applications. Why Python is suitable for machine learning? How Python is used in AI? What language is best for machine learning?

Python tutorial for beginners - Learn Python for Machine Learning and Web Development

TABLE OF CONTENT

  • 00:00:00 Introduction
  • 00:01:49 Installing Python 3
  • 00:06:10 Your First Python Program
  • 00:08:11 How Python Code Gets Executed
  • 00:11:24 How Long It Takes To Learn Python
  • 00:13:03 Variables
  • 00:18:21 Receiving Input
  • 00:22:16 Python Cheat Sheet
  • 00:22:46 Type Conversion
  • 00:29:31 Strings
  • 00:37:36 Formatted Strings
  • 00:40:50 String Methods
  • 00:48:33 Arithmetic Operations
  • 00:51:33 Operator Precedence
  • 00:55:04 Math Functions
  • 00:58:17 If Statements
  • 01:06:32 Logical Operators
  • 01:11:25 Comparison Operators
  • 01:16:17 Weight Converter Program
  • 01:20:43 While Loops
  • 01:24:07 Building a Guessing Game
  • 01:30:51 Building the Car Game
  • 01:41:48 For Loops
  • 01:47:46 Nested Loops
  • 01:55:50 Lists
  • 02:01:45 2D Lists
  • 02:05:11 My Complete Python Course
  • 02:06:00 List Methods
  • 02:13:25 Tuples
  • 02:15:34 Unpacking
  • 02:18:21 Dictionaries
  • 02:26:21 Emoji Converter
  • 02:30:31 Functions
  • 02:35:21 Parameters
  • 02:39:24 Keyword Arguments
  • 02:44:45 Return Statement
  • 02:48:55 Creating a Reusable Function
  • 02:53:42 Exceptions
  • 02:59:14 Comments
  • 03:01:46 Classes
  • 03:07:46 Constructors
  • 03:14:41 Inheritance
  • 03:19:33 Modules
  • 03:30:12 Packages
  • 03:36:22 Generating Random Values
  • 03:44:37 Working with Directories
  • 03:50:47 Pypi and Pip
  • 03:55:34 Project 1: Automation with Python
  • 04:10:22 Project 2: Machine Learning with Python
  • 04:58:37 Project 3: Building a Website with Django

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

Complete Python Bootcamp: Go from zero to hero in Python 3

Machine Learning A-Z™: Hands-On Python & R In Data Science

Python and Django Full Stack Web Developer Bootcamp

Complete Python Masterclass

Python Programming Tutorial | Full Python Course for Beginners 2019 👍

Top 10 Python Frameworks for Web Development In 2019

Python for Financial Analysis and Algorithmic Trading

Building A Concurrent Web Scraper With Python and Selenium