Ticket #4207: TestMyExternalObj.mo

File TestMyExternalObj.mo, 2.3 KB (added by Lennart Ochel, 8 years ago)
Line 
1package TestMyExternalObj
2 class MyExternalObj
3 extends ExternalObject;
4 function constructor
5 input Integer size=3;
6 output MyExternalObj outMyExternalObj;
7
8 external "C" outMyExternalObj=initMyExternalObj(size);
9 annotation(Include="
10 #include <stdio.h>
11 #include <stdlib.h> /* for Linux malloc and exit */
12 #include <string.h>
13
14 void* initMyExternalObj(int size)
15 {
16 int i=0;
17
18 double *extObj = (double*)malloc(size*sizeof(double));
19 if(extObj == NULL)
20 printf(\"Not enough memory\");
21
22 for(i=0; i<size; i++)
23 if(i < 2)
24 extObj[i] = 1.0;
25 else
26 extObj[i] = extObj[i-1]+extObj[i-2];
27
28 return (void*)extObj;
29 }");
30 end constructor;
31
32 function destructor
33 input MyExternalObj inMyExternalObj;
34
35 external "C" closeMyExternalObj(inMyExternalObj) ;
36 annotation(Include="
37 #include <stdio.h>
38 #include <stdlib.h> /* for Linux malloc and exit */
39 #include <string.h>
40
41 /* Destructor */
42 void closeMyExternalObj(void *object)
43 {
44 /* Release storage */
45 double *extObj = (double*)object;
46 if (object == NULL)
47 return;
48
49 free(extObj);
50 }");
51 end destructor;
52 end MyExternalObj;
53
54 function readFromMyExternalObj
55 input MyExternalObj extObj;
56 input Integer i;
57 output Real y;
58
59 external "C" y=readFromMyExternalObj(extObj, i);
60 annotation(Include="
61 #include <stdio.h>
62 #include <stdlib.h> /* for Linux malloc and exit */
63 #include <string.h>
64
65 double readFromMyExternalObj(void* object, int i)
66 {
67 double *extObj = (double*)object;
68 return extObj[i-1];
69 }");
70 end readFromMyExternalObj;
71
72 model Test
73 parameter Integer size = 5;
74 final parameter Integer size_ = size;
75 parameter MyExternalObj MyExtObj=MyExternalObj(size_);
76 parameter Real p1 = readFromMyExternalObj(MyExtObj, 1);
77 Real p2 = readFromMyExternalObj(MyExtObj, 2);
78 Real p3 = readFromMyExternalObj(MyExtObj, 3);
79 Real p4 = readFromMyExternalObj(MyExtObj, 4);
80 Real p5 = readFromMyExternalObj(MyExtObj, 5);
81 end Test;
82end TestMyExternalObj;