8

为了获得一些学习经验,我正在尝试在 Python 3.2 的扩展中将 SDL(1.2.14)的一些部分包装在 Cython 中。

我在弄清楚如何将 C 结构直接包装到 Python 中时遇到问题,能够直接访问其属性,例如:

struct_name.attribute

比如我想取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;

并且能够在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?

4

1 回答 1

2

在一个简单的情况下,如果 struct 是不透明的,它很简单:

cdef extern from "foo.h":
    struct spam:
        pass

当您想要访问成员时,有几个选项,在文档中有很好的介绍:

http://docs.cython.org/src/userguide/external_C_code.html#styles-of-struct-union-and-enum-declaration

于 2015-03-12T13:32:43.253 回答