【问题标题】:How to wrap C structs in Cython for use in Python?如何在 Cython 中包装 C 结构以在 Python 中使用?
【发布时间】:2012-07-12 01:19:48
【问题描述】:

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

我无法弄清楚如何将 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?

【问题讨论】:

标签: python struct sdl cython word-wrap


【解决方案1】:

在一个简单的情况下,如果 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

【讨论】:

    猜你喜欢
    • 2014-06-26
    • 2016-10-25
    • 2021-03-21
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多