Can we use C code in Python?

Question:

I know that Python provides an API so you can call Python interpreter in C code, but what I want is the opposite.

My program needs to use some C API, so the code must be written in C. But I also want to package the program with Python. Which means I want to invoke those C function or executables in Python. Is that possible?

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? Is that possible? If I write the C code into executable, which means it becomes a command, can I invoke it in Python directly?

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?

Asked By: dspjm

||

Answers:

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

Answered By: ffriend

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.

Answered By: Jacqui Gurto