You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Cython中引用pygame等外部C库类型?编译SDL类型报错求解

问题:Cython优化Pygame游戏时的类型声明编译错误

背景

我正在用Pygame开发游戏,尝试通过Cython提升运行速度。目前发现性能瓶颈集中在surface.subsurface()、pygame.transform.scale()这类Pygame方法的调用上。作为优化第一步,我想给Pygame Surface变量声明合适的C类型,参考Cython文档后,在.pyx文件中添加了以下代码:

cdef extern from "src_c/include/_pygame.h":
    ctypedef struct pgSurfaceObject

我下载了Pygame源码,其中_pygame.h里的pgSurfaceObject定义如下:

typedef struct {
    PyObject_HEAD struct SDL_Surface *surf;
    int owner;
    struct pgSubSurface_Data *subsurface; /* ptr to subsurface data (if a
                                           * subsurface)*/
    PyObject *weakreflist;
    PyObject *locklist;
    PyObject *dependency;
} pgSurfaceObject;

编译错误

执行编译命令:

$ python setup.py build_ext --inplace

得到以下错误输出:

Compiling raycasting.pyx because it changed.
[1/1] Cythonizing raycasting.pyx
running build_ext
building 'raycasting' extension
gcc -pthread -B /home/user/software/miniconda3/envs/pygame/compiler_compat -DNDEBUG -fwrapv -O2 -Wall -fPIC -O2 -isystem /home/user/software/miniconda3/envs/pygame/include -fPIC -O2 -isystem /home/user/software/miniconda3/envs/pygame/include -fPIC -I/home/user/software/miniconda3/envs/pygame/include/python3.11 -c raycasting.c -o build/temp.linux-x86_64-cpython-311/raycasting.o
In file included from raycasting.c:767:0:
src_c/include/_pygame.h:385:19: error: unknown type name ‘SDL_Rect’
     PyObject_HEAD SDL_Rect r;
                   ^~~~~~~~
src_c/include/_pygame.h:412:5: error: unknown type name ‘SDL_Joystick’
     SDL_Joystick *joy;
     ^~~~~~~~~~~~
src_c/include/_pygame.h:450:5: error: unknown type name ‘SDL_PixelFormat’
     SDL_PixelFormat *vfmt;
     ^~~~~~~~~~~~~~~
src_c/include/_pygame.h:451:5: error: unknown type name ‘SDL_PixelFormat’
     SDL_PixelFormat vfmt_data;
     ^~~~~~~~~~~~~~~
error: command '/usr/bin/gcc' failed with exit code 1

疑问

  • 是否必须添加SDL作为依赖?
  • 我只想让Cython识别通过Conda安装的已编译Pygame包中的类型,有没有更简便的方式引用头文件?比如通过setup.py配置?

我的setup.py代码如下:

from setuptools import setup
from Cython.Build import cythonize

import Cython.Compiler.Options
Cython.Compiler.Options.annotate = True

setup(
    ext_modules=cythonize(
        'raycasting.pyx', annotate=True, language_level=3),
)

内容的提问来源于stack exchange,提问作者Jan Wilamowski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 15:52:55