是否可以获取Delphi 7中指针指向的类型的大小? [英] Is it possible to get the size of the type that a pointer points to in Delphi 7?

查看:294
本文介绍了是否可以获取Delphi 7中指针指向的类型的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在以下函数中获取任何记录"类型的大小.但似乎不起作用:

I want to get the size of any "record" type in following function. But seems it doesn't work:

function GetDataSize(P : Pointer) : Integer;
begin
  Result := SizeOf(P^); // **How to write the code?**
end;

例如,以下记录的大小为8个字节

For example, the size of following record is 8 bytes

SampleRecord = record
 Age1 : Integer;
 Age2 : Integer;
end;

但是GetDataSize(@a)始终返回1(当然,a是SampleRecord类型的变量).我该怎么办?

But GetDataSize(@a) always returns 1 (a is a variable of SampleRecord type of course). What should I do?

我注意到Delphi有一个过程 procedure New(var P:Pointer),该过程可以分配与P指向的类型的大小相对应的存储块.如何获得尺寸?

I noticed that Delphi has a procedure procedure New(var P: Pointer) which can allocate the memory block corresponds to the size of the type that P points to. How can it gets the size?

推荐答案

New知道要分配多少内存的原因是New编译器魔术.这是一种内置语言,因此当编译器看到您调用它时,它会将其重写为以下内容:

The reason New knows how much memory to allocate is that New is compiler magic. It's a language built-in, so when the compiler sees you call it, it rewrites it to something like this:

// New(foo);
foo := System._New(SizeOf(foo^), TypeInfo(TypeOf(foo^)));

TypeOf此处是出于说明目的的组合Delphi函数.编译器知道foo的声明类型,因为它知道所有变量声明的位置.您可以在 System.pas 中查看_New的实现. Dispose也会发生类似的重写,因此它知道在释放内存之前要执行哪种终结处理.

TypeOf here is a made-up Delphi function for expository purposes. The compiler knows the declared type of foo because it knows where all your variable declarations are. You can look at the implementation of _New in System.pas. Similar rewriting occurs for Dispose so it knows what kind of finalization to do before freeing the memory.

变量声明的思想是编译时概念.在运行时,它们不再存在.在运行时,指针只是一个地址.指向的类型是在编译时确定的.类型是决定事物大小的因素.

The ideas of variables and declarations are compile-time concepts. At run time, they cease to exist. At run time, a pointer is just an address. The type of what it points to was determined at compile time. Types are what determine something's size.

如果您需要编写一个函数来接受指向具有不同大小的多个事物的指针,那么您只需提供第二个参数即可描述第一个参数所指向的内容.

If you need to write a function that accepts pointers to multiple things with different sizes, then you'll just have to provide a second parameter that describes what the first one points to.

在此处查看另一个问题,"如何知道类型是var ."询问者想知道如何在仅给出变量地址的情况下确定有关该变量的更多信息.

Check out another question here, "How to know what type is a var." The asker wondered how to determine more information about a variable given only its address.

这篇关于是否可以获取Delphi 7中指针指向的类型的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆