diff --git a/docs/src/userguide/external_C_code.rst b/docs/src/userguide/external_C_code.rst index 242068dceb3a0fb673b7dc5679d439f0ce07c035..00cf99691360c3f1b792465505bc2d22b8384ab8 100644 --- a/docs/src/userguide/external_C_code.rst +++ b/docs/src/userguide/external_C_code.rst @@ -124,6 +124,35 @@ A few more tricks and tips: cdef extern from *: ... +Implementing functions in C +--------------------------- + +When you want to call C code from a Cython module, usually that code +will be in some external library that you link your extension against. +However, you can also directly compile C (or C++) code as part of your +Cython module. In the ``.pyx`` file, you can put something like:: + + cdef extern from "spam.c": + void order_spam(int tons) + +Cython will assume that the function ``order_spam()`` is defined in the +file ``spam.c``. If you also want to cimport this function from another +module, it must be declared (not extern!) in the ``.pxd`` file:: + + cdef void order_spam(int tons) + +For this to work, the signature of ``order_spam()`` in ``spam.c`` must +match the signature that Cython uses, in particular the function must +be static: + +.. code-block:: c + + static void order_spam(int tons) + { + printf("Ordered %i tons of spam!\n", tons); + } + + .. _struct-union-enum-styles: Styles of struct, union and enum declaration diff --git a/tests/run/extern_impl.srctree b/tests/run/extern_impl.srctree new file mode 100644 index 0000000000000000000000000000000000000000..3c7583c4590b99158930be7e62d22e5f0161cc69 --- /dev/null +++ b/tests/run/extern_impl.srctree @@ -0,0 +1,29 @@ +PYTHON setup.py build_ext --inplace +PYTHON -c "import foo" +PYTHON -c "import a" + +######## setup.py ######## + +from Cython.Build import cythonize +from distutils.core import setup + +setup( + ext_modules = cythonize("*.pyx"), +) + +######## foo.pxd ######## + +cdef void bar() + +######## foo.pyx ######## + +cdef extern from "bar_impl.c": + void bar() + +######## bar_impl.c ######## + +static void bar() {} + +######## a.pyx ######## + +from foo cimport bar