当前位置:网站首页>Automatically obtain the position offset of member variables inside the structure
Automatically obtain the position offset of member variables inside the structure
2022-06-12 23:06:00 【Hold false and think true】
Ask a question : The name of a structure and the name of a member variable in the structure are known , How to get the position offset of the member variable in the structure ?
Take up a C Examples of language structures :
typedef struct _node {
int value32;
long value64;
struct _node * next;
} Node;
As shown above , How to know next stay Node Position offset in ?
Such a simple structure can be calculated manually . But if it is a relatively large structure , There are tens or hundreds of member variables , To know the relative position shift of a variable in the middle , It's a little bit more complicated .
Even if you can count , Some other member variables may be added before it in the future , When the time comes , The calculated value is invalid , Count again .
therefore , If you use a program to calculate the offset of a specified member variable , What should be done ?
You can do this with the following line of code .
#define GET_OFFSET(_type, _member) ((unsigned long)(&((_type *)0)->_member))
Explain it. :
Address 0 As a Node Instance address , So that nature can use ->next get next Member variables , Then we can get the address character next The address of the member variable .
Because the address of the instance itself is from 0 Start , So here we get next The address of the member variable is naturally offset .
So why is this value not negative ?
I guess , This is because the compiler assumes that the instance is in the heap , In the process space of the program , The heap address increases from the low address to the high address , So it's a positive number . Or maybe it's not that complicated at all , The compiler simply thinks that the address of the member variable is gradually increasing relative to the starting address of the instance , Not gradually decreasing .
The complete program code is as follows :
#include <stdio.h>
#define GET_OFFSET(_type, _member) ((unsigned long)(&((_type *)0)->_member))
typedef struct _node {
int value32;
long value64;
struct _node * next;
} Node;
int main()
{
unsigned long offset = GET_OFFSET(Node, next);
printf("offset of next = %ld\n", offset);
return 0;
}
The execution result of the above procedure is :
offset of next = 16
This method is right for C++ Class of also applies , But only for public Type to calculate the position offset , as follows :
#include <iostream>
using namespace std;
#ifdef __cplusplus
#define ENV "CPP"
#else
#define ENV "C"
#endif
#define GET_OFFSET(_type, _member) ((unsigned long)(&((_type *)0)->_member))
class Node {
public:
virtual int getValue32() {
return value32; }
virtual int getValue64() {
return value64; }
Node(int v32=0, int v64=0) : value32(v32), value64(v64) {
}
private:
int value32;
long value64;
public:
Node * next;
};
int main()
{
unsigned long offset = GET_OFFSET(Node, next);
unsigned long offset_in_c_way = (unsigned long)(&((Node *)0)->next);
cout << "ENV=" << ENV <<endl;
cout << "offset of next = " << offset << endl;
return 0;
}
The execution result is :
ENV=CPP
offset of next = 24
there offset The reason why it has become 24 instead of 16, Because in Node There is a virtual table pointer at the top of the instance , Occupied 8 Bytes , therefore next The position of the member variable is offset from 16 Bytes become 24 byte .
Another question is coming , What is the use of calculating the offset of member variables within a structure ?
See the next section for details .
( End )
边栏推荐
- Is there any risk in opening a securities account? How to open an account safely?
- 【LeetCode】300. Longest ascending subsequence
- 【LeetCode】103. Zigzag sequence traversal of binary tree
- MYSQL 行转列、列转行、多列转一行、一行转多列
- Shardingsphere-proxy-5.0.0 deployment table implementation (I)
- 【LeetCode】69. Square root of X
- PostgreSQL 中文社区黑龙江分会和辽宁分会成立啦!
- The fate of Internet people is that it is difficult to live to 30?
- Pytorch中的梯度累加【在实验时,由于GPU显存限制,遇到batch_size不能再增大的情况。为解决该问题,使用梯度累加方法】
- Database system composition
猜你喜欢

Mysql concat_ws、concat函数使用

基于51单片机的酒精检测仪

Zhengzhou University of light industry -- development and sharing of harmonyos pet health system

The development trend of digital collections!

Shardingsphere-proxy-5.0.0 deployment table implementation (I)

C语言:如何给全局变量起一个别名?

Photoshop:PS如何实现放大图片不模糊

Model over fitting - solution (II): dropout

数字藏品的发展趋势!

Record 5 - the serial port of stm32f411ceu6 realizes the sending and receiving of fixed length data and variable length data
随机推荐
A 42 year old senior executive of a large factory reminds people aged 30-39 that these six habits that make you stronger should be developed as soon as possible
同花顺股票账户开户安全吗
About three-tier architecture and MVC
Analysis report on investment and development trend of gap base of Chinese traditional medicine 2022 ~ 2028
Several Tsinghua students I know have left
启牛帮开通的股票账户是安全可信的吗?
C language: how to give an alias to a global variable?
Photoshop:PS如何实现放大图片不模糊
反走样/抗锯齿技术
C language: how to give an alias to a global variable?
Anti aliasing / anti aliasing Technology
Colab tutorial (super detailed version) and colab pro/colab pro+ usage evaluation
MySQL基础篇视图的总结
Go时间格式化 赋值
Research Report on market supply and demand and strategy of China's digital camera lens industry
Leetcode 890 finding and replacing patterns [map] the leetcode path of heroding
ASP. Net core Middleware
CST learning: four element array design of circular patch antenna (II) array formation and combination results
Research Report on water sports shoes industry - market status analysis and development prospect forecast
The carrying capacity of L2 level ADAS increased by more than 60% year-on-year in January, and domestic suppliers "emerged"