Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Execute a String of Code in Python
Next article icon

Using C codes in Python | Set 2

Last Updated : 18 Mar, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report

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




import work
  
print ("GCD : ", work.gcd(35, 42))
  
print ("\ndivide : ", work.divide(42, 8))
  
print ("\navg : ", work.avg([1, 2, 3]))
  
p1 = work.Point(1, 2)
p2 = work.Point(4, 5)
print ("\ndistance : ", work.distance(p1, p2))
 
 

Output :

  GCD : 7    divide : (5, 2)    avg : 2.0    distance : 4.242640687119285  

 
Issue ?
Now the work done above has an issue that for the overall packaging of C and Python code together, using ctypes to access C code that has been compiled, one has to make sure that the shared library gets placed in a location, where the work.py module can find it. One possibility is to put the resulting libsample.so file in the same directory as the supporting Python code.

So, if the C library is installed elsewhere, then path has to be adjusted accordingly. If it is installed as a standard library on the machine, then ctypes.util.find_library() function can be used.

Code #2 : Path Example




from ctypes.util import find_library
  
find_library('m')
  
find_library('pthread')
  
find_library('sample')
 
 

Output :

  /usr/lib/libm.dylib    /usr/lib/libpthread.dylib    /usr/local/lib/libsample.so  

Again, ctypes won’t work at all if it can’t locate the library with the C code. ctypes.cdll.LoadLibrary() is used to load the C library, once it’s location is known.




_mod = ctypes.cdll.LoadLibrary(_path)
 
 


Next Article
Execute a String of Code in Python

M

manikachandna97
Improve
Article Tags :
  • Python
  • python-utility
Practice Tags :
  • python

Similar Reads

  • Convert String to Set in Python
    There are multiple ways of converting a String to a Set in python, here are some of the methods. Using set()The easiest way of converting a string to a set is by using the set() function. Example 1 : [GFGTABS] Python s = "Geeks" print(type(s)) print(s) # Convert String to Set set_s = set(s
    1 min read
  • Convert Set to String in Python
    Converting a set to a string in Python means changing a group of unique items into a text format that can be easily read and used. Since sets do not have a fixed order, the output may look different each time. For example, a set {1, 2, 3} can be turned into the string "{1, 2, 3}" or into "{3, 1, 2}"
    3 min read
  • Python code formatting using Black
    Writing well-formatted code is very important, small programs are easy to understand but as programs get complex they get harder and harder to understand. At some point, you can’t even understand the code written by you. To avoid this, it is needed to write code in a readable format. Here Black come
    3 min read
  • set copy() in python
    The copy() method returns a shallow copy of the set in python. If we use "=" to copy a set to another set, when we modify in the copied set, the changes are also reflected in the original set. So we have to create a shallow copy of the set such that when we modify something in the copied set, change
    2 min read
  • Execute a String of Code in Python
    Sometimes, we encounter situations where a Python program needs to dynamically execute code stored as a string. We will explore different ways to execute these strings safely and efficiently. Using the exec function exec() function allows us to execute dynamically generated Python code stored in a s
    2 min read
  • Sets in Python
    A Set in Python is used to store a collection of items with the following properties. No duplicate elements. If try to insert the same item again, it overwrites previous one.An unordered collection. When we access all items, they are accessed without any specific order and we cannot access items usi
    9 min read
  • Python String Module
    The string module is a part of Python's standard library and provides several helpful utilities for working with strings. From predefined sets of characters (such as ASCII letters, digits and punctuation) to useful functions for string formatting and manipulation, the string module streamlines vario
    4 min read
  • Keywords in Python | Set 2
    Python Keywords - Introduction Keywords in Python | Set 1  More keywords:16. try : This keyword is used for exception handling, used to catch the errors in the code using the keyword except. Code in "try" block is checked, if there is any type of error, except block is executed. 17. except : As expl
    4 min read
  • Count set bits using Python List comprehension
    set bits means finding how many 1s are in the binary form of a number. The set bit is any bit that is 1. List comprehension offers a quick and simple way to count these set bits. In this article, we will count set bits using Python list comprehension. Using bin()bin() function converts a number to b
    2 min read
  • Hash Set in Python
    Hash Set is a data structure that stores unique elements in an unordered manner and provides highly efficient operations for searching, inserting, and deleting elements. Python Set data type is a built-in implementation of a hash set. Python sets are implemented using hash tables, where each element
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences