I want to invoke those C function or executables in python. Is that possible.

Yes, you can write C code that can be imported into Python as a module. Python calls these extension modules. You can invoke it from Python directly, an example from the documentation:

Python Code

import example
result = example.do_something()

C Code

static PyObject * example(PyObject *self)
{
    // do something
    return Py_BuildValue("i", result);
}

If I want the C code to be a library, which means I use it with #include and linkage of the *.o likely in python, how to do it or is that possible.

You build it as a shared library *.dll or *.so You can also investigate using distutils to distribute your module.

If I write the C code into executable, which means it becomes a command, can I invoke it in python directly?

If you write a *.exe then you are doing the opposite (invoking Python from C). The method you choose (exe vs shared library) depends on if you want a "C program with some Python" or a "Python program with some C".

Also, I heard that python code can be compiled, does that mean we can execute the code without the source file? Are the output files binary files? Does it improve performance?

Python reads *.py files and compiles to *.pyc bytecode files when you run it. The bytecode is then run in the Python virtual machine. This means "executing the same file is faster the second time as recompilation from source to bytecode can be avoided." (from the Python glossary) So if you haven't edited your *.py files, it will run the *.pyc. You can distribute *.pyc files without *.py files, however they are not encrypted and can be reverse-engineered.

Answer from Jacqui Gurto on Stack Overflow
Top answer
1 of 2
128

I want to invoke those C function or executables in python. Is that possible.

Yes, you can write C code that can be imported into Python as a module. Python calls these extension modules. You can invoke it from Python directly, an example from the documentation:

Python Code

import example
result = example.do_something()

C Code

static PyObject * example(PyObject *self)
{
    // do something
    return Py_BuildValue("i", result);
}

If I want the C code to be a library, which means I use it with #include and linkage of the *.o likely in python, how to do it or is that possible.

You build it as a shared library *.dll or *.so You can also investigate using distutils to distribute your module.

If I write the C code into executable, which means it becomes a command, can I invoke it in python directly?

If you write a *.exe then you are doing the opposite (invoking Python from C). The method you choose (exe vs shared library) depends on if you want a "C program with some Python" or a "Python program with some C".

Also, I heard that python code can be compiled, does that mean we can execute the code without the source file? Are the output files binary files? Does it improve performance?

Python reads *.py files and compiles to *.pyc bytecode files when you run it. The bytecode is then run in the Python virtual machine. This means "executing the same file is faster the second time as recompilation from source to bytecode can be avoided." (from the Python glossary) So if you haven't edited your *.py files, it will run the *.pyc. You can distribute *.pyc files without *.py files, however they are not encrypted and can be reverse-engineered.

2 of 2
16

You don't necessary need to extend Python (which is not trivial, btw), but can use foreign function interface such as ctypes.

🌐
GitHub
github.com › python › cpython › blob › main › Python › import.c
cpython/Python/import.c at main · python/cpython
Create a code object for a frozen module. ... Returns True if the module name is of a frozen package. ... Returns True if the module name corresponds to a built-in module.
Author: python
Discussions

How is python able to use c code?
There is an API in the C that you can use to interact with Python objects from C code, which is the same API that python uses internally to bootstrap itself in many cases. There are good guides in the official python docs for how to make a python module in C in detail, but the overview of how it's done is: Create a c source file Include the Python.h header file, which exists on any system with the python interpreter installed. There are functions and macros in the Python.h header that allow you to create a python module "object", which can be imported, and to specify which functions should be part of that object, and for each function, you can specify it's python function signature, although from a C perspective, all the values passed into a python function are just python objects (pointers to a PyObject struct) The PyObject structure is the fundamental data type inside the python interpreter. It is a polymorphic struct, which is really neat. You can implement polymorphism and object orientation inside of C with some neat struct casting tricks, and that's what python does. Therefore, there are macros to convert the PyObject struct coming into your function to a PyListObject struct, for example, and then there are more C APIs for doing what you need to do to a list (append, insert, delete, etc.) Now, once your C code is all written up, you need to compile it. This would be tricky, except that python's setuptools (setup.py) has utilities for including C extensions in your library. So, you can just compile it through that tool while mostly ignoring the complexity of compiling and linking manually. At the end of the day, if you created a module named foo in C, you should be able to simply import and use it like any other python module. For example, the csv module is implemented entirely in C, although you'd probably never know it! More on reddit.com
🌐 r/learnpython
11
6
September 18, 2021
How to import a C file into python - Stack Overflow
In addition to the question linked in the previous comment (which is about calling C functions from Python), check out Calling an external command in Python. You may be able to compile our C code normally into a program and call that program from Python. What you definitely cannot do is executing ... More on stackoverflow.com
🌐 stackoverflow.com
How can a Python package use C, like NumPy?
You can write and create a C program, that has interfaces that allows it to be used from python. It's written in C code, implements specific functions, exports them, and can use special c helper functions created by python developers to work with data that python understands. https://docs.python.org/3/extending/extending.html More on reddit.com
🌐 r/learnpython
4
6
February 9, 2023
Auto-import PS modules in VS code

Sure, the powershell extension for vs code opens a terminal and that loads the profile script. I believe it uses a different profile from the default though. You can always find your terminal session profile with the $profile variable.

More on reddit.com
🌐 r/vscode
4
10
December 30, 2019
🌐
Minimatech
minimatech.org › importing-c-code-into-python-2
Import C Code in Python (Part 2) – Minimatech
Cython can be considered a language of its own that has its own syntax, even though it is so similar to python syntax, that’s why it is somewhat more difficult than simple ways to integrate C with python such as ctypes for example. But it gives so much flexibility and sometimes using Cython code and importing it into python gives same results as pure C code.
🌐
Reddit
reddit.com › r/learnpython › how is python able to use c code?
r/learnpython on Reddit: How is python able to use c code?
September 18, 2021 -

I was always curious how python modules in c work. I know how to write and use a python c module, but i dont know how it works internally. Can anyone put me in the right path where can i start, an article or sthm or try to explain. And are there any simple tutorials to implement that sort of thing. Like calling .so files from your language etc...

Top answer
1 of 1
3
There is an API in the C that you can use to interact with Python objects from C code, which is the same API that python uses internally to bootstrap itself in many cases. There are good guides in the official python docs for how to make a python module in C in detail, but the overview of how it's done is: Create a c source file Include the Python.h header file, which exists on any system with the python interpreter installed. There are functions and macros in the Python.h header that allow you to create a python module "object", which can be imported, and to specify which functions should be part of that object, and for each function, you can specify it's python function signature, although from a C perspective, all the values passed into a python function are just python objects (pointers to a PyObject struct) The PyObject structure is the fundamental data type inside the python interpreter. It is a polymorphic struct, which is really neat. You can implement polymorphism and object orientation inside of C with some neat struct casting tricks, and that's what python does. Therefore, there are macros to convert the PyObject struct coming into your function to a PyListObject struct, for example, and then there are more C APIs for doing what you need to do to a list (append, insert, delete, etc.) Now, once your C code is all written up, you need to compile it. This would be tricky, except that python's setuptools (setup.py) has utilities for including C extensions in your library. So, you can just compile it through that tool while mostly ignoring the complexity of compiling and linking manually. At the end of the day, if you created a module named foo in C, you should be able to simply import and use it like any other python module. For example, the csv module is implemented entirely in C, although you'd probably never know it!
🌐
Readthedocs
reptate.readthedocs.io › developers › python_c_interface.html
Tutorial: Interfacing Python and C code — RepTate 1.4.0 documentation
Our C function c_square is now wrapped into a Python function do_square_using_c. To use it in a RepTate module, simply import the function by including in the module header.
🌐
Python Tips
book.pythontips.com › en › latest › python_c_extension.html
22. Python C extensions — Python Tips 0.1 documentation
In the python file, first the ctypes module is imported. Then the CDLL function of the ctypes module is used to load the shared lib file we created. The functions defined in the C lib are now available to us via the adder variable. When adder.add_int() is called, internally a call is made to ...
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › using-c-codes-in-python-set-1
Using C codes in Python | Set 1 - GeeksforGeeks
July 11, 2025 - Using ctypes : Python ctypes will come to play but make sure the C code, that is to be converted, has been compiled into a shared library that is compatible with the Python interpreter (e.g., same architecture, word size, compiler, etc.). Further the libsample.so file has been placed in the same directory as the work.py. Let's understand work.py now. Code #2 : Python module that wraps around resulting library to access it ... # work.py import ctypes import os # locating the 'libsample.so' file in the # same directory as this file _file = 'libsample.so' _path = os.path.join(*(os.path.split(__file__)[:-1] + (_file, ))) _mod = ctypes.cdll.LoadLibrary(_path) Code #3 : Accessing code
🌐
DigitalOcean
digitalocean.com › community › tutorials › calling-c-functions-from-python
Calling C Functions from Python | DigitalOcean
Technical tutorials, Q&A, events — This is an inclusive place where developers can find or lend support and discover new ways to contribute to the community.
🌐
Medium
medium.com › nabla-squared › how-to-use-c-code-in-python-582491e572d1
How to use C code in Python. … and should we do this? | by Dorian Lazar | Nabla Squared | Medium
May 31, 2021 - After installation, simply replace python with pypy when executing a Python script. So, instead of: ... As you will see in the benchmark at the end of this article, this method can make your code considerably faster and in some situations (as is the case with the simple…
🌐
Towards Data Science
towardsdatascience.com › home › latest › write your own c-extension to speed up python by 100x
Write Your Own C-extension to Speed Up Python by 100x | Towards Data Science
March 5, 2025 - The solution for this is to wrap the C-function in a Python module. You’re already familiar with these; think of time, os, and sys e.g. We’ll call our module Fastcount. At the end of this part we’ll have our module installed so you can ...
🌐
Klein Embedded
kleinembedded.com › home › calling c code from python
Calling C code from Python - Klein Embedded
January 31, 2023 - To create Python bindings for C or C++ code, there a several packages to choose from such as ctypes, CFFI, Cython, PyBind11, Boost.Python and more. You can try these out for yourself, but I am going to keep it simple and use the built-in ctypes package.
🌐
Quora
quora.com › How-can-I-run-C-code-in-Python
How to run C code in Python - Quora
Answer (1 of 8): I am assuming that you want to run your C code using Python language(interpreter) not a Python script to run a .c or .exe file. You can do it by calling subprocess for that you will need subprocess and os module. [code]import sys import subprocess import os prog = r''' #includ...
🌐
Nablasquared
nablasquared.com › how-to-use-c-code-in-python
How to use C code in Python - Nabla Squared
May 30, 2021 - We cannot provide a description for this page right now
🌐
Real Python
realpython.com › python-bindings-overview
Python Bindings: Calling C or C++ From Python – Real Python
March 18, 2026 - One of the big advantages of ctypes is that it’s part of the Python standard library. It was added in Python version 2.5, so it’s quite likely you already have it. You can import it just like you do with the sys or time modules. ... All of the code to load your C library and call the function will be in your Python program.
🌐
Medium
medium.com › @afomalhaut › how-to-import-c-in-python-d85324c5680c
How to import C in Python. In this article I am going to tell you… | by Alexander Fomalhaut | Medium
June 2, 2025 - In this article I am going to tell you how to implement a function in C, to compile it and import in Python. This can be helpful for boosting performance in some certain code sections in your Python application. Below I will describe and implement the algorithm of the longest common subsequence (https://en.wikipedia.org/wiki/Longest_common_subsequence) in Python and C importing it into Python.
🌐
YouTube
youtube.com › watch
How to use C from Python? - #9 - YouTube
Welcome to Learning at Lambert Labs session #9. This week, Amelia Crowther, explains how to use pre-existing C code from Python modules.In Today's Learning S...
Published: June 9, 2021
🌐
Cython
cython.readthedocs.io › en › latest › src › tutorial › external.html
Calling C functions - Cython's Documentation - Read the Docs
Pure Python syntax which allows static Cython type declarations in pure Python code, following PEP-484 type hints and PEP 526 variable annotations. To make use of C data types in Python syntax, you need to import the special cython module in the Python module that you want to compile, e.g.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-call-a-c-function-in-python
How to Call a C function in Python | GeeksforGeeks
November 1, 2023 - Python is an object-oriented language and it uses functions to reduce the repetition of the code. In this article, we will get to know what are parts, How to Create processes, and how to call them.In Python, there is a reserved keyword "def" which we use to define a function in Python, and after "de
🌐
Quora
quora.com › What-is-the-easiest-way-possible-to-embed-C-Code-into-Python
What is the easiest way possible to embed C Code into Python? - Quora
Answer (1 of 6): By “embed” I’m going to assume that you mean “create a binary module, written in C and compiled as a shared object (.so) or dynamic link library (.DLL) which can be loaded by the CPython interpreter and which exposes functionality to the interpreter.” Of course you ...