Wednesday, 15 January 2014

delphi - Is there any way to declare a const reference to a method at compile-time? -



delphi - Is there any way to declare a const reference to a method at compile-time? -

i'm working on script interpreter, i've managed working state. has compiler parses script , generates bytecode, , vm executes bytecode.

at heart of interpreter loop giant case statement looks this:

case currentopcode.operation of op_1: doop1(currentopcode); op_2: doop2(currentopcode); ... op_n: doopn(currentopcode); end;

profiling tells me that, whatever reason, script execution spending important amount of time within case statement, seems unusual me, i'm looking way optimize it. obvious solution, since operation functions have same signature, create array of method pointers indexed opcode's operation value. operation declared enum, , nice able declare const array if add together more opcodes in future, compiler can remind me update array.

since method pointer stores runtime state, (the self reference object it's running against,) can't create const array of method pointers. (nor thought anyway, it's quite i'll end more 1 script running @ same time.) methods syntactic sugar anyway. like:

procedure tmyobject.dosomething(x, y: integer);

really means:

procedure tmyobject_dosomething(self: tmyobject; x, y: integer);

so should able declare function pointer type in latter form , assign way, , i'd have explicitly pass self first parameter when invoke it. compiler doesn't that.

type topcodeproc = procedure (self: tscriptvm; opcode: topcode); const opcode: topcodeproc = tscriptvm.doop1; [dcc error]: e2009 incompatible types: 'regular procedure , method pointer'

i've tried different variations on seek compile, give errors. there way compile?

declaration:

const opcode: array[toperation] of pointer = ( @tscriptvm.doop1, @tscriptvm.doop2, ... @tscriptvm.doopn );

call:

topcodeproc(opcode[currentopcode.operation])(self, currentopcode);

more cool stuff:

var opcodeprocs: array[toperation] of topcodeproc absolute opcode;

much nicer syntax phone call method:

opcodeprocs[currentopcode.operation](self, currentopcode);

good thing because of absolute constant compiler prevents assigning opcodeprocs variable!

delphi

No comments:

Post a Comment