Extending Python with C or C++ It is quite easy to add new built-in modules to Python, if you know how to program in C. Such extension modules can do two things that can't be done directly in Python: they can implement new built-in object types, and they can call C library functions and system calls.
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.
You don't necessary need to extend Python (which is not trivial, btw), but can use foreign function interface such as ctypes.
Yes, it is possible to extend Python with C/C++.
Have a look at the documentation: Extending Python with C or C++
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With