[fpc-pascal] Calling a function by name (as string) read froma text file
Tomas Hajny
XHajT03 at mbox.vol.cz
Wed Oct 10 18:33:19 CEST 2007
Jilani Khaldi wrote:
>> Did you implement the record exactly as shown? This error normally
>> occurs
>> if you have fields in your record that you don't mention in your typed
>> const declaration.
>
> {$mode objfpc} -> Error!
> {$mode delphi} -> Ok!
> ...
> type
> TSetupFuncMapping = record
> x: array of double;
> name:string;
> func: SetupFunc;
> end;
>
> const
> SFM: array[0..2] of TSetupFuncMapping = (
> (x: nil; name: 'SetupFunction_1'; func: SetupFunction_1),
> (x: nil; name: 'SetupFunction_2'; func: SetupFunction_2),
> (x: nil; name: 'SetupFunction_3'; func: SetupFunction_3));
I only get a RTE when compiling and running the following with 2.0.4, not
a compile time error.
Tomas
{$MODE OBJFPC}
uses
SysUtils;
type
SetupFun = function(const vect: array of double): double;
MyRec = record
x: array of double;
myFunName: ShortString; // function name to evoke
end;
type
TSetupFuncMapping = record
x: array of double;
name:string;
func: SetupFun;
end;
function SetupFunction_1 (const vect: array of double): double;
begin
SetupFunction_1 := 1;
end;
function SetupFunction_2 (const vect: array of double): double;
begin
SetupFunction_2 := 2;
end;
function SetupFunction_3 (const vect: array of double): double;
begin
SetupFunction_3 := 3;
end;
function SetMeUp(const x1: array of double): double;
var
i: integer;
sum: double;
begin
sum := 0.0;
for i := 0 to High(x1) do
sum := sum + x1[i];
result := sum;
end;
const
SFM: array[0..3] of TSetupFuncMapping = (
(x: nil; name: 'SetupFunction_1'; func: @SetupFunction_1),
(x: nil; name: 'SetupFunction_2'; func: @SetupFunction_2),
(x: nil; name: 'SetMeUp'; func: @SetMeUp),
(x: nil; name: 'SetupFunction_3'; func: @SetupFunction_3));
// main
var
MR: MyRec;
y: double;
st: string;
f: text;
i, j, count: integer;
begin
// read MR from a text file...
assign(f, 'data.txt');
{$I-}
reset(f);
{$I+}
readln(f, MR.myFunName);
readln(f, count);
setlength(MR.x,count+1);
for i := 0 to count do
readln(f, MR.x[i]);
closefile(f);
writeln(MR.myFunName);
writeln(High(MR.x));
for i := 0 to High(MR.x) do
begin
writeln(MR.x[i]);
for J := 0 to 3 do
if SFM [J].Name = MR.MyFunName [J] then
y := SFM [J].Func (MR.X);
st := Format('Value: %6.5f', [y]);
writeln(st);
setlength(MR.x,0);
end;
readln;
end.
More information about the fpc-pascal
mailing list