1 /* ----------------------------------------------------------------------------- 2 * carrays.i 3 * 4 * SWIG library file containing 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(int nelements) { %} 24 #ifdef __cplusplus 25 %{ return new TYPE[nelements]; %} 26 #else 27 %{ return (TYPE *) calloc(nelements,sizeof(TYPE)); %} 28 #endif 29 %{} 30 31 static void delete_##NAME(TYPE *ary) { %} 32 #ifdef __cplusplus 33 %{ delete [] ary; %} 34 #else 35 %{ free(ary); %} 36 #endif 37 %{} 38 39 static TYPE NAME##_getitem(TYPE *ary, int index) { 40 return ary[index]; 41 } 42 static void NAME##_setitem(TYPE *ary, int index, TYPE value) { 43 ary[index] = value; 44 } 45 %} 46 47 TYPE *new_##NAME(int nelements); 48 void delete_##NAME(TYPE *ary); 49 TYPE NAME##_getitem(TYPE *ary, int index); 50 void NAME##_setitem(TYPE *ary, int index, TYPE value); 51 52 %enddef 53 54 55 /* ----------------------------------------------------------------------------- 56 * %array_class(TYPE,NAME) 57 * 58 * Generates a class wrapper around a C array. The class has the following 59 * interface: 60 * 61 * struct NAME { 62 * NAME(int nelements); 63 * ~NAME(); 64 * TYPE getitem(int index); 65 * void setitem(int index, TYPE value); 66 * TYPE * cast(); 67 * static NAME *frompointer(TYPE *t); 68 * } 69 * 70 * ----------------------------------------------------------------------------- */ 71 72 %define %array_class(TYPE,NAME) 73 %{ 74 typedef TYPE NAME; 75 %} 76 typedef struct { 77 /* Put language specific enhancements here */ 78 } NAME; 79 80 %extend NAME { 81 82 #ifdef __cplusplus 83 NAME(int nelements) { 84 return new TYPE[nelements]; 85 } 86 ~NAME() { 87 delete [] self; 88 } 89 #else 90 NAME(int nelements) { 91 return (TYPE *) calloc(nelements,sizeof(TYPE)); 92 } 93 ~NAME() { 94 free(self); 95 } 96 #endif 97 98 TYPE getitem(int index) { 99 return self[index]; 100 } 101 void setitem(int index, TYPE value) { 102 self[index] = value; 103 } 104 TYPE * cast() { 105 return self; 106 } 107 static NAME *frompointer(TYPE *t) { 108 return (NAME *) t; 109 } 110 111 }; 112 113 %types(NAME = TYPE); 114 115 %enddef 116 117