【发布时间】:2019-07-12 15:50:23
【问题描述】:
我有一个将 void 指针作为参数的函数。我想向这个函数传递一个指向结构的指针,然后在函数中访问该结构的值。
//the struct
struct s{
int val;
};
//the function tries to access the object
int callback(void* p_obj)
{
//try creating a new struct based on p_obj
s2 = *(struct s*)p_obj;
std::cout << "VALUE IN CALLBACK: ";
std::cout << s2.val << std::endl; //prints a big-ass int
return 0;
}
//main calls the function
int main()
{
s s1;
s1.val = 42;
void* p1 = &s;
//show some output
std::cout << "s1.val: ";
std:cout << s1.val << std::endl; //prints 42
//std::cout << "p1->val: ";
//std:cout << *(struct s*)p1->val << std::endl; //does not compile
s p2 = *(struct s*)p1;
std::cout << "p2.val: ";
std:cout << p2.val << std::endl; //prints 42
//call the function
callback(&p1);
return 0;
}
我希望回调函数中的输出是
VALUE IN CALLBACK: 42
VALUE IN CALLBACK: 42
但是,相反,我认为它正在打印内存地址
VALUE IN CALLBACK:1989685088
VALUE IN CALLBACK:1989685088
试图直接访问 void 指针的成员会导致错误。
int callback(void* p_obj)
{
std::cout << "VALUE IN CALLBACK: ";
std::cout << (struct s*)p_obj->val << std::endl;
}
error: 'void*' is not a pointer-to-object type
这是为什么?如何访问 void* 指向的结构的成员?
编辑:修正了文章中的一些错别字
【问题讨论】:
-
投票结束是一个错字。
s2 = *(struct s)p_obj;必须是s2 = *(struct s*)p_obj; -
为什么要编写类似 C 的代码?显然有人是teaching you c++ in wrong way(链接是给你的老师的)。
-
Marek,我遵循公司风格指南。 耸耸肩
-
这里有官方cpp core guidelines。
标签: c++