这是传递 numpy 数组的一个微小但完整的示例
逻辑上到外部 C 函数
fc( int N, double* a, double* b, double* z ) # z = a + b
使用 Cython。
(这对于熟悉这一点的人来说肯定是众所周知的。
欢迎评论。
最后更改:2011 年 2 月 23 日,Cython 0.14。)
首先阅读或浏览Cython 构建 http://docs.cython.org/src/quickstart/build.html
and Cython 与 NumPy http://docs.cython.org/src/tutorial/numpy.html .
2 steps:
-
python f-setup.py build_ext --inplace
turns f.pyx
and fc.cpp
-> f.so
,一个动态库
-
python test-f.py
import f
loads f.so
; f.fpy( ... )
呼叫 Cfc( ... )
.
python f-setup.py
uses distutils
运行 cython、编译并链接:
cython f.pyx -> f.cpp
编译f.cpp
and fc.cpp
link f.o fc.o
-> f.so
,
python 的动态库import f
将加载。
对于学生,我建议:画出这些步骤的图表,
查看下面的文件,然后下载并运行它们。
(distutils
是一个巨大而复杂的包,用于
制作用于分发的 Python 包并安装它们。
这里我们只使用其中的一小部分来编译和链接到f.so
。
这一步与 Cython 无关,但可能会令人困惑;
.pyx 中的简单错误可能会导致 g++ 编译和链接出现大量晦涩的错误消息。
也可以看看distutils 文档 http://docs.python.org/distutils
and/or
关于 distutils 的 SO 问题 https://stackoverflow.com/questions/tagged/distutils+python .)
Like make
, setup.py
将重新运行cython f.pyx
and g++ -c ... f.cpp
if f.pyx
比f.cpp
.
为了清理,rm -r build/
.
替代方案setup.py
将在脚本或 Makefile 中单独运行这些步骤:
cython --cplus f.pyx -> f.cpp # see cython -h
g++ -c ... f.cpp -> f.o
g++ -c ... fc.cpp -> fc.o
cc-lib f.o fc.o -> dynamic library f.so
.
修改cc-lib-mac
包装纸
下面是您的平台和安装:它不漂亮,但是很小。
对于 Cython 包装 C 的真实示例,
查看几乎任何文件中的 .pyx 文件SciKit http://scikits.appspot.com/scikits .
也可以看看:适用于 NumPy 用户的 Cython http://docs.cython.org/src/userguide/numpy_tutorial.html
and 所以问题/标记/cython https://stackoverflow.com/questions/tagged/cython .
要解压以下文件,
比如说,将批次剪切粘贴到一个大文件中cython-numpy-c-demo
,
然后在 Unix 中(在一个干净的新目录中)运行sh cython-numpy-c-demo
.
#--------------------------------------------------------------------------------
cat >f.pyx <<\!
# f.pyx: numpy arrays -> extern from "fc.h"
# 3 steps:
# cython f.pyx -> f.c
# link: python f-setup.py build_ext --inplace -> f.so, a dynamic library
# py test-f.py: import f gets f.so, f.fpy below calls fc()
import numpy as np
cimport numpy as np
cdef extern from "fc.h":
int fc( int N, double* a, double* b, double* z ) # z = a + b
def fpy( N,
np.ndarray[np.double_t,ndim=1] A,
np.ndarray[np.double_t,ndim=1] B,
np.ndarray[np.double_t,ndim=1] Z ):
""" wrap np arrays to fc( a.data ... ) """
assert N <= len(A) == len(B) == len(Z)
fcret = fc( N, <double*> A.data, <double*> B.data, <double*> Z.data )
# fcret = fc( N, A.data, B.data, Z.data ) grr char*
return fcret
!
#--------------------------------------------------------------------------------
cat >fc.h <<\!
// fc.h: numpy arrays from cython , double*
int fc( int N, const double a[], const double b[], double z[] );
!
#--------------------------------------------------------------------------------
cat >fc.cpp <<\!
// fc.cpp: z = a + b, numpy arrays from cython
#include "fc.h"
#include <stdio.h>
int fc( int N, const double a[], const double b[], double z[] )
{
printf( "fc: N=%d a[0]=%f b[0]=%f \n", N, a[0], b[0] );
for( int j = 0; j < N; j ++ ){
z[j] = a[j] + b[j];
}
return N;
}
!
#--------------------------------------------------------------------------------
cat >f-setup.py <<\!
# python f-setup.py build_ext --inplace
# cython f.pyx -> f.cpp
# g++ -c f.cpp -> f.o
# g++ -c fc.cpp -> fc.o
# link f.o fc.o -> f.so
# distutils uses the Makefile distutils.sysconfig.get_makefile_filename()
# for compiling and linking: a sea of options.
# http://docs.python.org/distutils/introduction.html
# http://docs.python.org/distutils/apiref.html 20 pages ...
# https://stackoverflow.com/questions/tagged/distutils+python
import numpy
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
# from Cython.Build import cythonize
ext_modules = [Extension(
name="f",
sources=["f.pyx", "fc.cpp"],
# extra_objects=["fc.o"], # if you compile fc.cpp separately
include_dirs = [numpy.get_include()], # .../site-packages/numpy/core/include
language="c++",
# libraries=
# extra_compile_args = "...".split(),
# extra_link_args = "...".split()
)]
setup(
name = 'f',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules,
# ext_modules = cythonize(ext_modules) ? not in 0.14.1
# version=
# description=
# author=
# author_email=
)
# test: import f
!
#--------------------------------------------------------------------------------
cat >test-f.py <<\!
#!/usr/bin/env python
# test-f.py
import numpy as np
import f # loads f.so from cc-lib: f.pyx -> f.c + fc.o -> f.so
N = 3
a = np.arange( N, dtype=np.float64 )
b = np.arange( N, dtype=np.float64 )
z = np.ones( N, dtype=np.float64 ) * np.NaN
fret = f.fpy( N, a, b, z )
print "fpy -> fc z:", z
!
#--------------------------------------------------------------------------------
cat >cc-lib-mac <<\!
#!/bin/sh
me=${0##*/}
case $1 in
"" )
set -- f.cpp fc.cpp ;; # default: g++ these
-h* | --h* )
echo "
$me [g++ flags] xx.c yy.cpp zz.o ...
compiles .c .cpp .o files to a dynamic lib xx.so
"
exit 1
esac
# Logically this is simple, compile and link,
# but platform-dependent, layers upon layers, gloom, doom
base=${1%.c*}
base=${base%.o}
set -x
g++ -dynamic -arch ppc \
-bundle -undefined dynamic_lookup \
-fno-strict-aliasing -fPIC -fno-common -DNDEBUG `# -g` -fwrapv \
-isysroot /Developer/SDKs/MacOSX10.4u.sdk \
-I/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 \
-I${Pysite?}/numpy/core/include \
-O2 -Wall \
"$@" \
-o $base.so
# undefs: nm -gpv $base.so | egrep '^ *U _+[^P]'
!
# 23 Feb 2011 13:38