Cython编译C++源码异常:未显式调用外部函数则编译失败
Cython调用C++函数编译异常问题
该问题已在Cython的bug追踪系统中记录。参考Cython调用C库教程尝试调用C++函数,在尝试类式语法定义外部函数失败后,找到一种编译方式,但出现异常行为。
测试涉及4个文件:
hello.cpp
#include <iostream> void hello_from_cpp() { std::cout << "Hello from C++!" << std::endl; }
cpp_hello.pyx
# distutils: language = c++ # cython: language_level = 3 cpdef extern void hello_from_cpp() def myfun(): hello_from_cpp()
setup.py
from setuptools import setup, Extension from Cython.Build import cythonize setup( ext_modules=cythonize([ Extension("cpp_hello", ["cpp_hello.pyx", "hello.cpp"]) ]), )
main.py
import cpp_hello if __name__ == "__main__": cpp_hello.hello_from_cpp()
使用python setup.py build_ext --inplace或python setup.py build_ext -i编译后,运行python main.py可正常输出Hello from C++!。
但移除cpp_hello.pyx中未使用的myfun()定义后,编译失败,报错如下:
[1/1] Cythonizing cpp_hello.pyx running build_ext building 'cpp_hello' extension creating build creating build/temp.linux-x86_64-cpython-310 x86_64-linux-gnu-gcc -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -fPIC -I/usr/include/python3.10 -c cpp_hello.cpp -o build/temp.linux-x86_64-cpython-310/cpp_hello.o cpp_hello.cpp: In function ‘int __pyx_pymod_exec_cpp_hello(PyObject*)’: cpp_hello.cpp:3027:84: error: ‘hello_from_cpp’ was not declared in this scope 3027 | PyObject* wrapped = __Pyx_CFunc_9cpp_hello_void__lParen__rParennoexcept_to_py_(hello_from_cpp); | ^~~~~~~~~~~~~~ cpp_hello.cpp: At global scope: cpp_hello.cpp:2362:18: warning: ‘PyObject* __Pyx_CFunc_9cpp_hello_void__lParen__rParennoexcept_to_py_(void (*)())’ defined but not used [-Wunused-function] 2362 | static PyObject *__Pyx_CFunc_9cpp_hello_void__lParen__rParennoexcept_to_py_(void (*__pyx_v_f)(void)) { | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ error: command '/usr/bin/x86_64-linux-gnu-gcc' failed with exit code 1
我的目标是创建可被Python调用的C代码库,通过.pyx和setup.py文件,用cpdef而非cdef定义C函数的Python接口。
内容的提问来源于stack exchange,提问作者DanBC
相关产品推荐
相关产品推荐

