Search code examples
pythondistutils

Is it possible to mix C and Python in the same namespace?


I'd like to write a Python package to wrap a new C library I'm writing - it's all a bit of a learning exercise to be honest. I'd like to call the library spam (of course) and the C library is structured like this.

Spam/
    lib/
        foo.c
        Makefile
        libspam.a   /* Generated by Makefile */
        libspam.so  /* Generated by Makefile */

Let's say foo.c provides a single public function foo(char * bar).At the same time, I want to provide a Python package. I want to provide a wrapper to foo and another function, say safe_foo, under the same namespace. safe_foo is a Python function which performs some checks on bar then calls foo. They could be called like this

import spam

file='hello.txt'
foo(file)
safe_foo(file)

Is that possible?

A similar situation would be that I develop a Python package and then want to reimplement one function as a C function without breaking the API.

You might be able to see I'm kind of new to Python packaging...


Solution

  • The usual way of doing this is to prefix the C module with an underscore (e.g. _foo.so) and then have the Python module named normally (e.g. foo.py). foo performs an import of _foo and contains stubs that call the functions in the C module.