从成员指针投射到整个结构/类

问题描述 投票:0回答:2

请考虑以下代码:

#include <iostream>


struct bar {
  double a = 1.0;
  int b = 2;
  float c = 3.0;
};

void callbackFunction(int* i) {

  auto myStruct = reinterpret_cast<bar*>(i) - offsetof(bar, b);

  std::cout << myStruct->a << std::endl;
  std::cout << myStruct->b << std::endl;
  std::cout << myStruct->c << std::endl;

  //do stuff
}

int main() {

  bar foo;

  callbackFunction(&foo.b);

  return 0;
}

我必须定义一个回调函数,并且我想在该函数中使用一些其他信息。我定义了自己的结构,并将成员的地址传递给函数。在该函数中,我想通过强制转换来“检索”整个结构,但是指针似乎不匹配,因此我得到了错误的结果。我想我在投射时做错了什么,但是我不确定是什么?

c++ function struct casting callback
2个回答
1
投票

您缺少进行这项工作的演员。您需要先将字节转换为字节类型,然后再减去偏移量,然后重铸回bar*


0
投票

您将指针向后移动太多,b的偏移量为sizeof(double),所以大概为8,但表达式reinterpret_cast<bar*>(i) - offsetof(bar, b)将其向后移动sizeof(bar) * sizeof(double)

© www.soinside.com 2019 - 2024. All rights reserved.