Ste*_*rst 3 c delphi types parameter-passing
我想知道是否可以将声明的类型(在本例中为记录)传递给我的函数.我甚至不会问它是否不适用于该SizeOf()函数,因为它可以将类型作为参数.
我正在翻译C中的代码,我希望尽可能接近原始代码.C程序将PushArray和PushStruct声明为宏.由于Delphi没有宏支持,我试图将它们变成函数.
我用谷歌搜索了一下,似乎我可以使用泛型类型.就像function PushStruct<T>(Arena : Pmemory_arena; dtype : <T>)但你只能在一个面向对象的应用类型使用.
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;
Run Code Online (Sandbox Code Playgroud)
这是原始的C代码:
#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);
}
Run Code Online (Sandbox Code Playgroud)
C代码没有将类型传递给函数.预处理器正在扩展宏并计算大小.你可以从函数的原型中看到:
void *PushSize_(memory_arena *Arena, memory_index Size)
Run Code Online (Sandbox Code Playgroud)
由于您在Delphi中没有宏,因此无法安排直接翻译.就个人而言,如果是我,我不会尝试完全匹配C代码.我将传递大小并将其留给调用者使用SizeOf.我认为这不是一个可怕的负担.它仍然会给你留下非常接近文字翻译的东西 - 你所缺少的只是方便的宏.
如果你想使用泛型,你可以这样做,但它需要你使用静态方法.例如:
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;
Run Code Online (Sandbox Code Playgroud)
如果要返回类似于以下内容的类型指针:
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;
Run Code Online (Sandbox Code Playgroud)
显然你会知道用什么名字代替TMyClass!
我不相信泛型在这里很合适,因为我猜你想要尽可能的字面翻译.在这种情况下,我不会选择使用泛型.