Python Forum

Full Version: Python functions in C
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
how many of you have ever written a Python function in C, even if just for Python2? i am wanting to get some idea how hard this is to decide if it is worth pursuing.
I want to know how it works.
I read how to write Python module in C but it was too complicated for me back then.
i suspect the C code will have to deal with the internals of how Python stores data and interfaces to function (if the C code needs to call a function that is in Python).
I've written quite a few C functions for use by Python. I posted a couple of tutorials on the previous incarnation of python-forum. Metalburr (with my permission) reposted them in the Tutorial section.

https://python-forum.io/Thread-Creating-...ons-Part-1
https://python-forum.io/Thread-Creating-...ons-Part-2

I haven't tested the examples for several years but they should still compile with Python 3.x.

Do you have a (relatively) simple function in mind?

casevh
i was going to make one that called the kernel pivot_root() syscall. the os module doesn't have it.
i think maybe i still need to make my own .pivot_root() so i can integrate the installation. it looks like butter may be difficult for end users of my script that needs to call .pivot_root().

my script will run early in the system init steps, terminate or kill all processes, set up virtual memory file space for the system files, copy the system files to that space, switch / to that space, unmount the original system files, and start init all over from the beginning there. in the case of cloud instances, it will also detach and delete the system volume that was a copy of the system image it all was started from.
I have written C extensions modules for python. It is not very difficult, the C function needs to parse the python arguments, execute C code, possibly using python's C API to manipulate python datatypes, then convert and return the result.

I also wrote Cython code, which is very easy to do because cython writes the glue code for you.

I also wrote Swig code to wrap C/C++ libraries with python.
i would like to see simple examples. this means not some big script the somewhere deep in there it does what i want to learn. it should be something where the thing of interest is a substantial part if it. examples written to be examples are usually best.

does anyone know where i can find good examples that really work (even if it is something C is not needed for, such as making a new string which is the merge of all its arguments)?
The basic examples at the beginning of chapters 1 and 2 of extending and embedding python with C or C++ should help you. Try to compile them and run them completely.

When you gain more experience with this, you could use these tips and tricks about extension functions written in C.