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
Release the interpreter's import lock. ... On platforms without threads, this function does nothing. ... Changes code.co_filename to specify the passed-in file path.
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
What is the Pythonic way of storing credentials in code?
In this instance, I think that it depends on the application. There are a few different main types of applications (at least types that I write). Web service, written using flask, django or some other framework. For these I generally use environment variables, then load all of them in a config.py, or something like that. For instance consumer_secret = os.environ['SECRET'] would load the environment var SECRET into that variable. It has the added advantage of throwing an error if the variable is not set, making it simple to find stuff where not all the options are configured. This makes it simple to deploy. Heroku passes most of it's other service information through environment variables, so you can even use their tools to run your projects even if you don't use heroku. If you want to do this, you need something like forego or foreman . Then you can make a .env file with SECRET=*!)(8sdoaiu09109u09, a Procfile with web: command to start your app and your app will start with foreman start. You can also run arbitrary commands with foreman run command here User facing tools. For these, python has a builtin config file parser . I haven't used this too much, but from what I can tell, it's pretty easy to work with. Once you have a file to store it in, you can separate config by sections and if the section doesn't create, you can populate it and save the file. You can also use a command line flag to load a separate config file if you want with argparse . Internal tools. Either of the previous options works. It really boils down to personal preference at this point. Hope this helps. EDIT: formatting EDIT 2: Added argparse info. EDIT 3: Just noticed your comment on leaving a blank template. This is bad for a number of reasons. Firstly, if something is added to the config template and then pushed, users will not be required to update their configs, so there's a possibility that you won't even run into an issue until they're running the program (if you use import config and then try to use config.something in code, there will be an error). It's much easier to catch configuration issues at startup. Secondly, if you want to run more than one instance of the program, you need a separate copy of the code. More on reddit.com
🌐 r/learnpython
10
19
May 21, 2014
🌐
Minimatech
minimatech.org › importing-c-code-into-python-2
Import C Code in Python (Part 2) – Minimatech
Now we will write a Cython wrapper to wrap the C Structs and functions. In a Cython script i.e. a “.pyx” file, we should import the structs and the functions from the header file and wrap the C struct into a python Class and use the C functions as Class methods.
🌐
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 ...
🌐
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!
🌐
Python
docs.python.org › 3 › extending › extending.html
1. Extending Python with C or C++ — Python 3.14.7 documentation
Before you do this, however, it is important to check that the return value isn’t NULL. If it is, the Python function terminated by raising an exception. If the C code that called PyObject_CallObject() is called from Python, it should now return an error indication to its Python caller, so ...
🌐
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.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › using-c-codes-in-python-set-1
Using C codes in Python | Set 1 - GeeksforGeeks
July 11, 2025 - There is an extensive C programming API that Python provides but there are many different to deal with C. Code #1 : [work.c] C-Code that we are dealing.
🌐
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.
🌐
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 - This is the function that Python will call when it imports our module for the first time: We use PyModule_Create and pass it a reference to the PyModuleDef from the previous part. This will return a PyObject in which our C-function is wrapped. Check out the whole code here.
🌐
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.
🌐
Real Python
realpython.com › build-python-c-extension-module
Building a Python C Extension Module – Real Python
March 18, 2026 - Once it’s successfully built, fire up the interpreter to test run your Python C extension module: ... >>> import fputs >>> fputs.__doc__ 'Python interface for the fputs C library function' >>> fputs.__name__ 'fputs' >>> # Write to an empty file named `write.txt` >>> fputs.fputs("Real Python!", "write.txt") 13 >>> with open("write.txt", "r") as f: >>> print(f.read()) 'Real Python!'
🌐
TutorialsPoint
tutorialspoint.com › how-to-call-a-c-function-in-python
How to Call a C Function in Python
July 20, 2023 - CFFI example code: import cffi ffi = cffi.FFI() # Define the C function prototype ffi.cdef(""" int add(int a, int b); int multiply(int a, int b); """) # In practice, you would load your library: # lib = ffi.dlopen('./math_operations.so') # result ...
🌐
GitHub
github.com › python › cpython › blob › d93605de7232da5e6a182fd1d5c220639e900159 › Python › import.c
cpython/Python/import.c at d93605de7232da5e6a182fd1d5c220639e900159 · python/cpython
Release the interpreter's import lock. ... On platforms without threads, this function does nothing. ... Changes code.co_filename to specify the passed-in file path.
Author: python
🌐
GitHub
github.com › python › cpython › blob › 4336222407f4aab5944b8c90a08d9cf644db7aa2 › Python › import.c
cpython/Python/import.c at 4336222407f4aab5944b8c90a08d9cf644db7aa2 · python/cpython
Release the interpreter's import lock. ... On platforms without threads, this function does nothing. ... Changes code.co_filename to specify the passed-in file path.
Author: python
🌐
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 ...
🌐
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…
🌐
DEV Community
dev.to › erikwhiting88 › how-to-use-c-functions-in-python-7do
How to Use C Functions in Python - DEV Community
August 4, 2019 - 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.
🌐
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...