【发布时间】:2017-07-31 15:13:07
【问题描述】:
根据documentation,可以使用从 Cython 生成的 C 头文件。我按照Hello World 的例子没有问题,现在我想尝试一些不同的东西。我想使用公共声明来使用自定义方法。我的代码结构如下:
- hello.pyx
- setup.py
- main.c
hello.pyx
cdef public void say_hello():
print("Hello World")
setup.py
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [
Extension("hello", ["hello.pyx", "main.c"]),
]
setup(
name='Hello app',
cmdclass={'build_ext': build_ext},
ext_modules=ext_modules
)
main.c
#include "hello.h"
int main(void){
say_hello();
}
main.c 充当测试文件,以验证 say_hello() 方法是否按预期工作。
构建设置文件python3 setup.py build_ext 会产生以下输出。
running build_ext
skipping 'hello.c' Cython extension (up-to-date)
building 'hello' extension
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/include/python3.5m -c hello.c -o build/temp.linux-x86_64-3.5/hello.o
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/include/python3.5m -c main.c -o build/temp.linux-x86_64-3.5/main.o
In file included from main.c:1:0:
hello.h:26:1: error: unknown type name ‘PyMODINIT_FUNC’
PyMODINIT_FUNC inithello(void);
^
error:
command 'x86_64-linux-gnu-gcc' failed with exit status 1
hello.h 文件包含以下内容
/* Generated by Cython 0.25.2 */
#ifndef __PYX_HAVE__hello
#define __PYX_HAVE__hello
#ifndef __PYX_HAVE_API__hello
#ifndef __PYX_EXTERN_C
#ifdef __cplusplus
#define __PYX_EXTERN_C extern "C"
#else
#define __PYX_EXTERN_C extern
#endif
#endif
#ifndef DL_IMPORT
#define DL_IMPORT(_T) _T
#endif
__PYX_EXTERN_C DL_IMPORT(void) say_hello(void);
#endif /* !__PYX_HAVE_API__hello */
#if PY_MAJOR_VERSION < 3
PyMODINIT_FUNC inithello(void); // <-- Line 26
#else
PyMODINIT_FUNC PyInit_hello(void);
#endif
#endif /* !__PYX_HAVE__hello */
据我了解,gcc 似乎无法获得正确版本的 Python(我使用的是 Python 3.5)。有没有办法以某种方式设置它?另外,如果确实如此,为什么在我运行python3 setup.py build_ext 命令时不处理这个链接?
我对 C 没有太多经验,所以我可能会遗漏一些东西。
【问题讨论】: