main,py内容如下
1 import ctypes
2 import example
3 # 加载库
4
5 result = example.add_numbers(3, 4)
6 print(result) # 输出:7
example.pyx如下:
1 cdef int add_numbers(int a, int b):
2 return a + b
cythonize -i example.pyx结果:
example.c:966:12: warning: ‘__pyx_f_7example_add_numbers’ defined but not used [-Wunused-function]
966 | static int __pyx_f_7example_add_numbers(int __pyx_v_a, int __pyx_v_b) {
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
gcc -pthread -shared -B /home/lixixi/anaconda3/compiler_compat -L/home/lixixi/anaconda3/lib -Wl,-rpath=/home/lixixi/anaconda3/lib -Wl,--no-as-needed -Wl,--sysroot=/ /home/lixixi/todelete/tmppiu24481/home/lixixi/todelete/example.o -o /home/lixixi/todelete/example.cpython-37m-x86_64-linux-gnu.so
运行结果:
Traceback (most recent call last):
File "main.py", line 5, in <module>
result = example.add_numbers(3, 4)
AttributeError: module 'example' has no attribute 'add_numbers'
解决办法以及原理:
修改example.pyx如下:
1 def add_numbers(int a, int b):
2 return a + b
原理:
用 cdef
而不是 def
来定义方法。,cdef
方法只能从 cython
代码调用。
Python 函数是使用 def 语句定义的,它们将 Python 对象作为参数并返回 Python 对象。
C 函数是使用新的 cdef 语句定义的,他们采取 Python 对象或 C 值作为参数,并且可以返回 Python 对象或 C 值。