l0r*_*3nu 8 python struct sdl cython word-wrap
为了获得一些学习经验,我试图在Cython中包含SDL(1.2.14)的一些部分,用于Python 3.2的扩展.
我有一个问题,弄清楚如何将C结构直接包装到Python中,能够直接访问其属性,如:
struct_name.attribute
Run Code Online (Sandbox Code Playgroud)
例如,我想采用struct 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;
Run Code Online (Sandbox Code Playgroud)
并且能够在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 )
Run Code Online (Sandbox Code Playgroud)
目前,我已将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)
Run Code Online (Sandbox Code Playgroud)
我该如何实现SDL.Surface?
在简单的情况下,如果 struct 是不透明的,则简单如下:
cdef extern from "foo.h":
struct spam:
pass
Run Code Online (Sandbox Code Playgroud)
当您想要访问成员时,有几个选项,文档中详细介绍了这些选项: