8

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?

l0rdx3nu
  • 81
  • 1
  • 2
  • 2
    take a look [how class Person is implemented](http://stackoverflow.com/a/7622428/4279). Here's a more complete [example as a gist](https://gist.github.com/4e72cc3ac15408df452e#file_person.pyx) – jfs Jul 12 '12 at 01:57
  • Much appreciated. Just what I needed. Guess I should do a more thorough search next time. – l0rdx3nu Jul 12 '12 at 02:34
  • @l0rdx3nu is it still relevant for you to have this answered? – Saullo G. P. Castro May 24 '14 at 14:10

1 Answers1

2

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

Dima Tisnek
  • 11,241
  • 4
  • 68
  • 120