Easiest way to access C module in Python
Lele Gaifax
lele at metapensiero.it
Tue Nov 7 07:14:54 EST 2017
bartc <bc at freeuk.com> writes:
> But just staying with the "function with no arguments" for the minute (the
> equivalent of Hello World for this exercise), how would it be done in
> Cython? Would a working example be simple enough to show in a usenet post?
fred.c::
int fred(void) {
return 42;
}
life.pyx::
cdef extern:
int fred()
def life():
return fred()
setup.py::
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
setup(
ext_modules = cythonize([Extension("life", ["life.pyx", "fred.c"])])
)
$ python setup.py build_ext --inplace
Compiling life.pyx because it changed.
[1/1] Cythonizing life.pyx
running build_ext
building 'life' extension
creating build
creating build/temp.linux-x86_64-3.6
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fdebug-prefix-map=/build/python3.6-5reRaQ/python3.6-3.6.3=. -specs=/usr/share/dpkg/no-pie-compile.specs -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/tmp/ct/include -I/usr/include/python3.6m -c life.c -o build/temp.linux-x86_64-3.6/life.o
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fdebug-prefix-map=/build/python3.6-5reRaQ/python3.6-3.6.3=. -specs=/usr/share/dpkg/no-pie-compile.specs -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/tmp/ct/include -I/usr/include/python3.6m -c fred.c -o build/temp.linux-x86_64-3.6/fred.o
x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -specs=/usr/share/dpkg/no-pie-link.specs -Wl,-z,relro -specs=/usr/share/dpkg/no-pie-link.specs -Wl,-z,relro -g -fdebug-prefix-map=/build/python3.6-5reRaQ/python3.6-3.6.3=. -specs=/usr/share/dpkg/no-pie-compile.specs -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 build/temp.linux-x86_64-3.6/life.o build/temp.linux-x86_64-3.6/fred.o -o /tmp/ct/life.cpython-36m-x86_64-linux-gnu.so
$ python -c "import life; print(life.life())"
42
As other said, for a single function accepting no arguments and returning a
single value Cython may be an heavy tool, but I bet you can imagine more
complex situations...
ciao, lele.
--
nickname: Lele Gaifax | Quando vivrò di quello che ho pensato ieri
real: Emanuele Gaifas | comincerò ad aver paura di chi mi copia.
lele at metapensiero.it | -- Fortunato Depero, 1929.
More information about the Python-list
mailing list