c - Delphi - How to pass a 'Type' as a parameter -
i know if possible pass declared type (in case record) function. not ask if not sizeof()
function, because can take type parameter.
i'm translating code c , keep close original possible. c program declares pusharray , pushstruct macros. since delphi not have macro support, i'm trying turn them functions.
i've googled bit , seems possible use generic types. function pushstruct<t>(arena : pmemory_arena; dtype : <t>)
can use in oop type application.
function pushsize_(arena : pmemory_arena; size : memory_index) : pointer; begin assert((arena^.used + size) <= arena^.size); result := arena^.base + arena^.used; arena^.used := arena^.used + size; end; function pushstruct(arena : pmemory_arena; dtype : ?) : pointer; begin result := pushsize_(arena, sizeof(dtype)); end; function pusharray(arena : pmemory_arena; count: uint32; dtype : ?) : pointer; begin result := pushsize_(arena, (count)*sizeof(dtype)) end;
here original c code:
#define pushstruct(arena, type) (type *)pushsize_(arena, sizeof(type)) #define pusharray(arena, count, type) (type *)pushsize_(arena, (count)*sizeof(type)) void * pushsize_(memory_arena *arena, memory_index size) { assert((arena->used + size) <= arena->size); void *result = arena->base + arena->used; arena->used += size; return(result); }
the c code isn't passing type function. pre-processor expanding macro , computing size. can see prototype of function:
void *pushsize_(memory_arena *arena, memory_index size)
since don't have macros in delphi, cannot arrange direct translation. personally, if me not attempt match c code exactly. i'd pass size , leave caller use sizeof
. don't think that's terrible burden. still leaves close literal translation – missing convenience macros.
if wanted use generics, so, require use static method. instance:
type tmyclass = class class function pushsize(arena: pmemory_arena; size: memory_index): pointer; static; class function pushstruct<t>(arena: pmemory_arena): pointer; static; end; .... class function tmyclass.pushsize(arena: pmemory_arena; size: memory_index): pointer; begin result := ....; end; class function tmyclass.pushstruct<t>(arena: pmemory_arena): pointer; begin result := pushsize(arena, sizeof(t)); end;
if want return typed pointer this:
type tmyclass<t> = class type p = ^ t; class function pushsize(arena: pmemory_arena; size: memory_index): pointer; static; class function pushstruct(arena: pmemory_arena): p; static; end; .... class function tmyclass<t>.pushsize(arena: pmemory_arena; size: memory_index): pointer; begin result := ....; end; class function tmyclass<t>.pushstruct(arena: pmemory_arena): p; begin result := pushsize(arena, sizeof(t)); end;
obviously you'd know name use instead of tmyclass
!
i'm not convinced generics fit here because guess wanting literal translation possible. not choose use generics in scenario.
Comments
Post a Comment