1 /* ----------------------------------------------------------------------------- 2 * carrays.swg 3 * 4 * This library file contains macros that can be used to manipulate simple 5 * pointers as arrays. 6 * ----------------------------------------------------------------------------- */ 7 8 /* ----------------------------------------------------------------------------- 9 * %array_functions(TYPE,NAME) 10 * 11 * Generates functions for creating and accessing elements of a C array 12 * (as pointers). Creates the following functions: 13 * 14 * TYPE *new_NAME(int nelements) 15 * void delete_NAME(TYPE *); 16 * TYPE NAME_getitem(TYPE *, int index); 17 * void NAME_setitem(TYPE *, int index, TYPE value); 18 * 19 * ----------------------------------------------------------------------------- */ 20 21 %define %array_functions(TYPE,NAME) 22 %{ 23 static TYPE *new_##NAME(size_t nelements) { 24 return %new_array(nelements, TYPE); 25 } 26 27 static void delete_##NAME(TYPE *ary) { 28 %delete_array(ary); 29 } 30 31 static TYPE NAME##_getitem(TYPE *ary, size_t index) { 32 return ary[index]; 33 } 34 static void NAME##_setitem(TYPE *ary, size_t index, TYPE value) { 35 ary[index] = value; 36 } 37 %} 38 39 TYPE *new_##NAME(size_t nelements); 40 void delete_##NAME(TYPE *ary); 41 TYPE NAME##_getitem(TYPE *ary, size_t index); 42 void NAME##_setitem(TYPE *ary, size_t index, TYPE value); 43 44 %enddef 45 46 47 /* ----------------------------------------------------------------------------- 48 * %array_class(TYPE,NAME) 49 * 50 * Generates a class wrapper around a C array. The class has the following 51 * interface: 52 * 53 * struct NAME { 54 * NAME(int nelements); 55 * ~NAME(); 56 * TYPE getitem(int index); 57 * void setitem(int index, TYPE value); 58 * TYPE * cast(); 59 * static NAME *frompointer(TYPE *t); 60 * } 61 * 62 * Use 63 * 64 * %array_class_wrap(TYPE,NAME,GET,SET) 65 * 66 * if you want different names for the get/set methods. 67 * ----------------------------------------------------------------------------- */ 68 69 %define %array_class_wrap(TYPE,NAME,getitem,setitem) 70 %{ 71 typedef TYPE NAME; 72 %} 73 74 75 typedef struct { 76 } NAME; 77 78 %extend NAME { 79 80 NAME(size_t nelements) { 81 return %new_array(nelements, TYPE); 82 } 83 84 ~NAME() { 85 %delete_array(self); 86 } 87 88 TYPE getitem(size_t index) { 89 return self[index]; 90 } 91 92 void setitem(size_t index, TYPE value) { 93 self[index] = value; 94 } 95 96 TYPE * cast() { 97 return self; 98 } 99 100 static NAME *frompointer(TYPE *t) { 101 return %static_cast(t, NAME *); 102 } 103 }; 104 105 %types(NAME = TYPE); 106 107 %enddef 108 109 110 #ifndef %array_class 111 %define %array_class(TYPE,NAME) 112 %array_class_wrap(TYPE,NAME,getitem,setitem) 113 %enddef 114 #endif 115