如何在Cython中封装C结构体以供Python使用?

8

为了学习经验,我试图在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?


2
请看Person类的实现方式。这里有一个更完整的示例作为gist - jfs
非常感谢,正是我所需要的。下次猜想我应该进行更彻底的搜索。 - l0rdx3nu
@l0rdx3nu,你还需要这个问题的答案吗? - Saullo G. P. Castro
1个回答

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接