Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap C structs in Cython for use in Python?

For a bit of learning experience, I'm trying to wrap a few parts of SDL (1.2.14) in Cython in an extension for Python 3.2.

I am having a problem figuring out how to wrap C structs straight into Python, being able to access its attributes directly like:

struct_name.attribute

For example, I want to take the 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;

And be able to use it like so in 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 )

For right now, I have wrapped the SDL_SetVideoMode and SDL_Surface like this in a file called 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)

How should I implement SDL.Surface?

like image 547
l0rdx3nu Avatar asked Jul 12 '12 01:07

l0rdx3nu


1 Answers

In a simple case, if struct is opaque, it's as simple as:

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

When you want access to members, there are several options, well presented in the docs:

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

like image 83
Dima Tisnek Avatar answered Sep 21 '22 08:09

Dima Tisnek