Mikroelektronika MIKROE-724 データシート

ページ / 726
mikroBasic PRO for dsPIC30/33 and PIC24
MikroElektronika
209
Example: 
Example  demonstrates  the  usage  of  function  pointers.  It  is  shown  how  to  declare  a  procedural  type,  a  pointer  to 
function and finally how to call a function via pointer.
program Example;
typedef TMyFunctionType = sub function (dim param1, param2 as byte, dim param3 as word
as word ‘ First, define the procedural type
dim MyPtr as ^TMyFunctionType  ‘ This is a pointer to previously defined type
dim sample as word
sub function Func1(dim p1, p2 as byte, dim p3 as word) as word ‘ Now, define few functions 
which will be pointed to. Make sure that parameters match the type definition
  result = p1 and p2 or p3
end sub
sub function Func2(dim abc, def as bytedim ghi as word) as word  ‘ Another function of 
the same kind. Make sure that parameters match the type definition
  result =  abc * def + ghi
end sub
sub function Func3(dim first, yellow as bytedim monday as word) as word  ‘ Yet another 
function. Make sure that parameters match the type definition
  result =  monday - yellow - first
end sub
‘ main program:
main:
  MyPtr = @Func1            ‘ MyPtr now points to Func1                                           
  Sample = MyPtr^(1, 2, 3)  ‘ Perform function call via pointer, call Func1, the return 
value is 3
  MyPtr = @Func2            ‘ MyPtr now points to Func2                                           
  Sample = MyPtr^(1, 2, 3)  ‘ Perform function call via pointer, call Func2, the return 
value is 5                                          
  MyPtr = @Func3            ‘ MyPtr now points to Func3
  Sample = MyPtr^(1, 2, 3)  ‘ Perform function call via pointer, call Func3, the return 
value is 0
end.
@ Operator
The 
@
 operator constructs a pointer to its operand. The following rules are applied to 
@
:
- If 
X
 is a variable, 
@X
 returns a pointer to 
X
Note: If variable 
X
 is of array type, the 
@
 operator will return pointer to it’s first basic element, except when the left side 
of the statement in which 
X
 is used is an array pointer. 
        In this case, the 
@
 operator will return pointer to array, not to it’s first basic element.