根据documentation,可以使用从Cython生成的C头文件。我按照Hello World
的例子没有问题,现在我想尝试一些不同的东西。我想使用公共声明来使用自定义方法。我的代码结构如下:使用Cython生成的头文件
- 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经验,所以我可能会错过一些东西。
感谢您的回答@ead,找到标志的提示非常有用。 唉,在'main.c'的编译过程中,我得到了方法'inithello()'的隐式声明警告,后来在我尝试链接时抛出一个错误“未定义的inithello引用”。 使用Python2.7很好! – BitWhyz
@BitWhyz通过查看hello.h代码,我认为你应该在Python3中使用'PyInit_hello()'而不是'inithello()'。 – ead
它的工作!谢谢。我不明白为什么文档没有提到这一点。我会很感激挖掘更多的好资源。 – BitWhyz