source: project/wiki/Wrapping simple c structs @ 31663

Last change on this file since 31663 was 31663, checked in by arthurmaciel, 7 years ago

Removed unnecessary line break.

  • Property svnwiki:tags set to foreign define-foreign-type
File size: 889 bytes
Line 
1Here's a little example wrapping c structs in a scheme blob. Since they might be moved around by garbage collection, you cannot store pointers to them, but for simple structs it should suffice.
2
3<enscript highlight=scheme>
4(use lolevel)
5
6(foreign-declare "#include <SDL/SDL.h>")
7
8;; SDL_Rect is defined thusly:
9;
10;typedef struct{
11;  Sint16 x, y;
12;  Uint16 w, h;
13;} SDL_Rect;
14
15(define sizeof-SDL_Rect (foreign-value "sizeof(SDL_Rect)" int))
16
17(define-record sdl-rect buffer)
18
19(define-foreign-type sdl-rect scheme-pointer sdl-rect-buffer)
20
21(define sdl-rect-x
22  (foreign-lambda* short ((sdl-rect rect))
23    "C_return(((SDL_Rect*)rect)->x);"))
24
25(define sdl-rect-x-set!
26  (foreign-lambda* void ((sdl-rect rect) (short value))
27    "((SDL_Rect*)rect)->x = value;"))
28
29;; behold
30
31(define foo (make-sdl-rect (make-blob sizeof-SDL_Rect)))
32(sdl-rect-x-set! foo 30)
33(sdl-rect-x foo) ==> 30
34
35</enscript>
Note: See TracBrowser for help on using the repository browser.