获取结构的位置var AKA记录字段的偏移量 [英] Get Position of a struct var AKA Offset of record field

查看:149
本文介绍了获取结构的位置var AKA记录字段的偏移量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得一个结构/记录的位置。



说我有这个记录:

  type 
MyStruct = record
MyInteger:Integer;
MyInteger2:整数;
MyInteger3:整数;
MyFunc:function(FirstParam:WideString; SecondParam:String):Integer;
MyString:String;
MyString2:WideString;
MyPchar:pchar;
结束

正如你可以看到这个记录的大小为28个字节(7个vars x 4个字节)。基本上因为所有的var都是4字节的var(如整数)或指针(也是4字节)。
现在我们假设我们将这个结构体加载到一个内存地址(X = 0)中(这也意味着MyInteger的地址将为0)。
MyInteger3的地址(例如)将为8(注意X = 0!)
我如何能够动态地获取结构的位置(数字/地址)?



希望你们知道我的意思?
提前感谢。



BTW:
结构体中有任何Var总是4个字节吗?
编辑:
如果您修复spcae,这是错误的: String [100]

解决方案

您可以使用一些指针算术获得任何记录成员的偏移量:

  type 
PMyStruct = ^ MyStruct;

var
偏移:整数;
begin
偏移量:=整数(@(PMyStruct(nil).MyInteger3));
//或
// Offset:= Integer(Addr(PMyStruct(nil).MyInteger3));
结束

如果你想要功能的偏移量,你需要像这样编码:

  Offset:= Integer(@@ PMyStruct(nil).MyFunc); 
//或
// Offset:= Integer(Addr(@PMyStruct(nil).MyFunc));


I would like to get a "position" of a structure/record.

Say I have this record:

type
  MyStruct = record
    MyInteger   : Integer;
    MyInteger2  : Integer;
    MyInteger3  : Integer;
    MyFunc      : function (FirstParam : WideString; SecondParam : String) : Integer;
    MyString    : String;
    MyString2   : WideString;
    MyPchar     : pchar;
end;

As you can see this record has a size of 28 bytes (7 vars x 4 bytes). Basically because all the vars are either 4 byte vars (such as Integer) or pointers (also 4 bytes). Now let's say we have this struct loaded in an memory-address (X = 0) (which also means the address for MyInteger would be 0). The address of MyInteger3 (for example) would be 8 (be aware of the X = 0 !) How can I get the position (number/address) of the struct dynamically?

Hope you guys know what I mean? Thanks in advance.

BTW: Is any Var always 4 bytes in a struct? EDIT: This is wrong if you fix the spcae : String[100]

解决方案

You can get the offset of any record member using some pointer arithmetic:

type
  PMyStruct = ^MyStruct;

var
  Offset: Integer;
begin
  Offset := Integer(@(PMyStruct(nil).MyInteger3));
  // or:
  // Offset := Integer(Addr(PMyStruct(nil).MyInteger3));
end;

If you want the offset of the function you need to code it like this:

Offset := Integer(@@PMyStruct(nil).MyFunc);
// or:
// Offset := Integer(Addr(@PMyStruct(nil).MyFunc));

这篇关于获取结构的位置var AKA记录字段的偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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