为了学习经验,我试图在Python 3.2的扩展中使用Cython封装SDL(1.2.14)的一些部分。
我遇到了一个问题,即如何将C结构直接包装成Python,能够直接访问其属性,例如:
struct_name.attribute
例如,我想要使用结构体SDL_Surface:
typedef struct SDL_Rect {
Uint32 flags
SDL_PixelFormat * format
int w, h
Uint16 pitch
void * pixels
SDL_Rect clip_rect
int refcount
} SDL_Rect;
并且能够在Python中像这样使用:
import SDL
# initializing stuff
Screen = SDL.SetVideoMode( 320, 480, 32, SDL.DOUBLEBUF )
# accessing SDL_Surface.w and SDL_Surface.h
print( Screen.w, ' ', Screen.h )
现在,我已经将SDL_SetVideoMode和SDL_Surface封装在一个名为SDL.pyx的文件中。
cdef extern from 'SDL.h':
# Other stuff
struct SDL_Surface:
unsigned long flags
SDL_PixelFormat * format
int w, h
# like past declaration...
SDL_Surface * SDL_SetVideoMode(int, int, int, unsigned )
cdef class Surface(object):
# not sure how to implement
def SetVideoMode(width, height, bpp, flags):
cdef SDL_Surface * screen = SDL_SetVideoMode
if not screen:
err = SDL_GetError()
raise Exception(err)
# Possible way to return?...
return Surface(screen)
我该如何实现SDL.Surface?