User manual

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 nally 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, dene the procedural type
dim MyPtr as ^TMyFunctionType ‘ This is a pointer to previously dened type
dim sample as word
sub function Func1(dim p1, p2 as byte, dim p3 as word) as word Now, dene few functions
which will be pointed to. Make sure that parameters match the type denition
result = p1 and p2 or p3
end sub
sub function Func2(dim abc, def as byte, dim ghi as word) as word Another function of
the same kind. Make sure that parameters match the type denition
result = abc * def + ghi
end sub
sub function Func3(dim rst, yellow as byte, dim monday as word) as word ‘ Yet another
function. Make sure that parameters match the type denition
result = monday - yellow - rst
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 rst 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 rst basic element.