File: arraymember.i

package info (click to toggle)
swig 1.1p5-1
  • links: PTS
  • area: main
  • in suites: hamm
  • size: 9,448 kB
  • ctags: 5,025
  • sloc: cpp: 21,599; ansic: 13,333; yacc: 3,297; python: 2,794; makefile: 2,197; perl: 1,984; tcl: 1,583; sh: 736; lisp: 201; objc: 143
file content (68 lines) | stat: -rw-r--r-- 1,168 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// This file shows how one can access array members of structures and
// classes.

%module arraymember
%inline %{
#include "struct.h"

/* Create a structure for holding integer pointers */
typedef struct {
     int *iptr;
} IntArray;
%}

%addmethods IntArray {
  IntArray(int *iptr) {
    IntArray *i = (IntArray *) malloc(sizeof(IntArray));
    i->iptr = iptr;
    return i;
  }
  ~IntArray() {
    free(self);
  }
  int __getitem__(int index) {
    return self->iptr[index];
  }
  void __setitem__(int index, int val) {
    self->iptr[index] = val;
  }
};

// Now a "clever" typemap

// Return an IntArray instead of an int *
%typemap(memberout) IntArray * {
  static IntArray i;
  i.iptr = $source;
  $target = &i;
}

// Set an IntArray
%typemap(memberin) IntArray * {
  $target = $source->iptr;
}
  
// Now declare your structure (but in a different way).

struct foo {
  int a;
  IntArray *b;
};

// A helper function

%inline %{
  
  struct foo *bar(int n) {
    struct foo *f = (struct foo *) malloc(sizeof(struct foo));
    int i;
    f->a = n;
    f->b = (int *) malloc(n*sizeof(int));
    for (i = 0; i < n; i++)
      f->b[i] = i;
    return f;
  }
%}