Skip to content

template python packages including cython code, & c code for building python packages that wrap compiled c code

Notifications You must be signed in to change notification settings

alexland/compiled-c-extensions-in-python-libraries

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

37 Commits
 
 
 
 
 
 
 
 

Repository files navigation

generic directory structure of a cython package:

top-level (distribution root, aka entry points

+-- proj_dir
|	+-- __init__.py
|   +-- __main__.py
|	+-- wrapper.pyx
|	+-- wrapper.c
|	+-- lib
|		+-- cfunc.c
|		+-- cfunc.h
+-- setup.py
+-- MANIFEST.in
+-- runner
+-- README.md

note wrapper.c is generated via cython

note the importable module is created inside proj_dir, & is a .so file which is imported like a normal python module

steps:

    cd proj_dir    							# 1 level deep
    cython wrapper.pyx  					# cythonize the C src, creates 'wrapper.c'
    cd ..									# go up to root dir
    python3 setup.py build_ext --inplace	# build python package 

========

to wrap c functions in a python package:

  1. write the c functions in a src file w/ a c ext

  2. write function prototypes in a corresponding header file w/ h ext

  3. put both files in eg, a lib directory

  4. write the wrapper function in a pyx file

  5. put pyx file same location as lib dir

  6. reference in init.py

building a cython extension from a .pyx file

======

method 1

  • code .pyx file

  • create setup.py file

from distutils.core import setup
from Cython.Build import cythonize
		
setup(name="compiled ext module I",
		ext_modules=cythonize("hw.pyx"),
)
  • from shell: $> python3 setup.py build-ext --inplace

  • this will build a .so file, which can be imported and its fns called inside this namespace, like so:

  • import hw

============

method 2 (if no C libraries required & no unusual build req)

  • create .pyx file

  • import pyximport; pyximport.install()

  • import hw

About

template python packages including cython code, & c code for building python packages that wrap compiled c code

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published