我的项目中有许多类型的结构,另一个结构包含指向这些结构之一的指针。如,
struct one{int num = 1;};
struct two{int num = 2;};
struct three{int num = 3;};
// These structs hold many other values as well, but the first value is always `int num`.
我有另一个结构保存对这些结构的引用。我不得不使用
void*
因为我不知道将引用这些结构中的哪一个。struct Holder{void* any_struct};
我的问题是,我需要这些结构中的值,但我有一个
void
指针,我可以声明一个基结构,第一个变量是 int
,转换它,并用它来提取 num
来自这些结构的变量,例如:struct Base{int num};
((Base*) Holder->any_struct)->num
// Gives 1, 2 or 3
最佳答案
如果您只需要提取 num
,您可以使用 memcpy
.
假设它总是 int
并且永远在前,永远在场。
int num = 0;
memcpy(&num, Holder->any_struct, sizeof(int));
// Gives 1, 2 or 3 in num.
C99 标准第 6.7.2.1 条第 13 条:
A pointer to a structure object, suitably converted, points to its initial member. There may be unnamed padding within a structure object, but not at its beginning.
有关标准的更多信息 this answer .
关于c - 使用基本结构从 void* 中提取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58641549/