您需要一个 C 文件来包含 C 函数 (base_hello.c),一个 C 头文件来包含这些 C 函数的声明 (base_hello.h),以及一个 cython 文件来告诉 cython 如何转换这些 C 函数进入python函数(hello.pyx)。以下是它们各自包含的内容:
base_hello.c
#include <stdio.h>
#include "base_hello.h"
int print_hello_world(int N_prints){
for (int i=0; i<N_prints; i++){
printf("%i Hello World\n",i);
}
return 2*N_prints;
}
base_hello.h
int print_hello_world(int N_prints);
hello.pyx
cdef extern from "base_hello.h":
int print_hello_world(int N_prints);
def run_print_hello_world(N_prints):
return print_hello_world(N_prints)
然后你需要将 base_hello.c 编译成一个对象文件,然后将 hello.pyx 文件编译成一个共享对象,然后可以将它导入到 python 中。基本上 hello.pyx 告诉 Cython 如何将 C 函数转换为 python 函数。您可以使用根据 cython 文档创建的 setup.py 编译这些文件,也可以使用类似于以下编译命令的东西来编译这些文件,您肯定想在其中更改 python 实例的路径:
cython -v -2 hello.pyx
cc -shared -fPIC -I"/Users/michael/miniconda2/include/python2.7" -o hello.so hello.c base_hello.c
为了测试它是否有效,这里有一个简单的测试脚本 test_hello.py。
test_hello.py
import hello
for i in range(4):
print 'TESTING %i PRINTS'%i
hello.run_print_hello_world(i)
运行“python test_hello.py”应该会输出以下内容:
TESTING 0 PRINTS
TESTING 1 PRINTS
0 Hello World
TESTING 2 PRINTS
0 Hello World
1 Hello World
TESTING 3 PRINTS
0 Hello World
1 Hello World
2 Hello World