您需要一个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);
你好
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