Python Forum
interfacing C with Python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
interfacing C with Python
#1
starting to read up on interfacing C with Python. the first impression i get is that a lot of effort is being made to make Python bend down to the way C does things. i'd rather work with a API subset where C code must be coded Python-aware. a C function called from a Python script would get arguments in the form Python works with, with perhaps a set of C macros or functions that helps the C code work with it. the C code would then have to build the value to be returned and call a function to actually give them to be returned (else a return from C just returns a None). is there anything that does a C interface like this? all my intentions for C will be Python aware, or i will do the calls to unaware code in C.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
I'm not an expert in interfacing Python and C but I think the default API already works the way you described above. Extension modules use Python-aware C functions that get arguments in the form Python works with and parse them with the C macro PyArg_ParseTuple. When they return Python values they use the macro Py_BuildValue to create them. The problem with this API is that it forces you to write a lot of hybrid code, take care of reference counts, etc, so it is a slow process.

Before you jump into this, it would be a good idea to review existing tools that already interface Python and C as it is an old problem and many solutions have been developped, starting with the ctypes module, the Cython language, the Swig module. In my bookmarks, there are 3 modern modules that try to minimize the amount of boilerplate code and could be worth exploring, cffi, cppyy and pybind11.
Reply
#3
i was seeing a bunch of Python functions or classes for Python code to be able to do things that C needs like converting an int to 16 bits, or constructing arguments for a C function. i'm on pause right now due to a major hardware issue. to deal with that, i need to move to my backup laptop that still has a very old Ubuntu (14.04) on it. it needs a fresh install to be normal to me but i decided this is a good time to upgrade from 18.04 to 20.04. i'm also re-arranging partitions so / has more space. this laptop will become a compact server.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020