/tags/rel-2.0.2/Examples/test-suite/lextype.i

# · Swig · 54 lines · 23 code · 8 blank · 23 comment · 0 complexity · 71824c5b448a1e61437657631395c9e2 MD5 · raw file

  1. /*
  2. This module tests whether SWIG sets the '$lextype' variable
  3. correctly. This variable maintains the literal base name of the
  4. type in the wrapper code - it's therefore usually the same
  5. as '$basetype', but NOT ALWAYS.
  6. In the example below, the typemap definitions are written
  7. for any type of 'Animal', but are parameterized through
  8. preprocessor definitions. So when wrapping functions which
  9. explicitly reference Giraffes, the wrapper code can
  10. behave appropriately for that particular species.
  11. For this to work correctly however, it is critical that
  12. there is a variable which strictly preserves the name
  13. of the type. '$basetype' doesn't currently do this -
  14. it sometimes contains 'Giraffe' and sometimes (specifically
  15. the case of arrays) contains 'Animal'. Since existing
  16. code may rely on that behaviour, we create a new variable
  17. '$lextype' which does what we need.
  18. There is no need for any runtime test here, since if the
  19. code is not functioning properly it will fail to compile.
  20. */
  21. %module lextype
  22. %{
  23. #include <stdlib.h>
  24. %}
  25. %typemap(in) Animal ()
  26. {
  27. void *space_needed = malloc(HEIGHT_$1_lextype * WIDTH_$1_lextype);
  28. $1 = ($1_ltype)space_needed;
  29. }
  30. %typemap(in) Animal[2] ()
  31. {
  32. void *space_needed = malloc(2 * HEIGHT_$1_lextype * WIDTH_$1_lextype);
  33. $1 = ($1_ltype)space_needed;
  34. }
  35. %inline %{
  36. #define HEIGHT_Giraffe 100
  37. #define WIDTH_Giraffe 5
  38. typedef void * Animal;
  39. typedef Animal Giraffe;
  40. void eat(Giraffe g) {}
  41. void drink(Giraffe *g) {}
  42. Giraffe mate(Giraffe g[2]) { return g[0]; }
  43. %}