您可以使用 pygame C-API,即使它可能不打算以这种方式使用(这又引出了为什么 pygame 头文件与 pygame 包一起安装的问题)。
当 pygame 的下一个版本/构建发布时,针对这种“内部”API 构建的扩展可能会中断,除非 pygame 开发人员关心这些 C 头文件的 API/ABI 兼容性......
无论如何,这是一个例子:
C 扩展模块代码(red.c):
#include <Python.h>
#include <pygame/pygame.h>
static PyObject* fill_surface(PyObject* self, PyObject* args)
{
PyObject* py_surface = NULL;
if( !PyArg_ParseTuple(args, "O", &py_surface) )
return NULL;
PySurfaceObject* c_surface = (PySurfaceObject*) py_surface;
SDL_FillRect( c_surface->surf, 0, SDL_MapRGB(c_surface->surf->format, 255, 0, 0) );
return Py_None;
}
PyMethodDef methods[] = {
{"fill_surface", fill_surface, METH_VARARGS, "Paints surface red"},
{NULL, NULL, 0, NULL},
};
void initred()
{
Py_InitModule("red", methods);
}
用于构建 (Linux) 的 Makefile:
SOURCES = red.c
OBJECTS = $(SOURCES:.c=.o)
TARGET = red.so
CFLAGS += -Wall -O2 -g
CFLAGS += $(shell python-config --cflags)
CFLAGS += $(shell sdl-config --cflags)
LDFLAGS += $(shell sdl-config --libs)
all: $(TARGET)
clean:
$(RM) $(OBJECTS)
$(RM) $(TARGET)
$(TARGET): $(OBJECTS)
$(CC) -shared -o $@ $(OBJECTS) $(LDFLAGS)
$(OBJECTS): Makefile
Python测试代码:
import pygame
import red
pygame.init()
screen = pygame.display.set_mode( (640, 480) )
red.fill_surface(screen)
pygame.display.update()
pygame.time.delay(3000)