当前位置:网站首页>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 )
边栏推荐
- 度量学习(Metric Learning)【AMSoftmax、Arcface】
- 【LeetCode】53. Maximum subarray and
- MySQL row to column, column to row, multiple columns to one row, one row to multiple columns
- MOOG servo valve d634-341c/r40ko2m0nss2
- 反走样/抗锯齿技术
- The carrying capacity of L2 level ADAS increased by more than 60% year-on-year in January, and domestic suppliers "emerged"
- Database system composition
- PyTorch常用参数初始化方法:【均匀分布、正态(高斯)分布、Xavier、kaiming、正交矩阵、稀疏矩阵、常数、单位矩阵、零填充】
- The shutter library recommends sizer to help you easily create a responsive UI
- 模型过拟合-解决方案(二):Dropout
猜你喜欢

MySQL基础篇视图的总结

iShot

MYSQL 行转列、列转行、多列转一行、一行转多列

Heilongjiang Branch and Liaoning Branch of PostgreSQL Chinese community have been established!

Insight into China's smart medical industry in 2022

Mysql concat_ WS, concat function use

Gb28181 protocol -- alarm

Summary of MySQL foundation view

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

【Web技术】1348- 聊聊水印实现的几种方式
随机推荐
PostgreSQL 中文社区黑龙江分会和辽宁分会成立啦!
Analysis report on production and marketing demand and investment forecast of China's Melamine Industry from 2022 to 2028
Report on the "fourteenth five year plan" and strategic strategy recommendations for China's intellectual property protection industry 2022 ~ 2028
Gb28181 protocol -- alarm
【LeetCode】102. 二叉树的层序遍历
Pytorch common parameter initialization methods: [uniform distribution, normal (Gaussian) distribution, Xavier, Kaiming, orthogonal matrix, sparse matrix, constant, identity matrix, zero filling]
Mysql case when then函数使用
同花顺股票账户开户安全吗
About three-tier architecture and MVC
Lua date time
The Milvus graphical management tool Attu is coming!
lua 循环语句
Research Report on market supply and demand and strategy of tizanidine industry in China
Matters of parent-child class construction method in inheritance
CST learning: four element array design of circular patch antenna (II) array formation and combination results
【LeetCode】33. 搜索旋转排序数组
细数攻防演练中十大关键防守点
ImageView grayed, reflected, rounded, watermarked
[Part 7] source code analysis and application details of cyclicbarrier [key]
【LeetCode】5. 最长回文子串