在 C 中,void 指针如何取消引用回原始结构?
我无法为将队列作为链表管理的队列的 C 接口提供结构值。它以空指针的形式保存数据,以允许接口通用地管理任何数据。我将值作为指针引用传递,然后将其保存为空指针。后来当它返回时,我不知道如何将 void 指针转换回原始值。
我需要做什么?这是示例结构。
typedef struct MyData {
int mNumber;
} MyData;
为了简化一切,我创建了一个虚拟函数,可以用几行代码模拟所有内容。
void * give_and_go(void *data) {
void *tmp = data;
return tmp;
}
您可以看到它接受一个 void 指针,将其设置为局部变量,然后返回它。现在我需要取回原来的值。
MyData inVal;
inVal.mNumber = 100;
void * ptr = give_and_go(&inVal);
MyData outVal; // What converts ptr to the out value?
这就是我被困住的地方。我正在使用 Xcode,它不允许我简单地将 ptr 转换为 MyData 或我尝试过的各种替代方案。
任何帮助表示赞赏。
I am having trouble giving a struct value to a C interface for a queue that manages the queue as a linked list. It holds onto the data as void pointers to allow the interface to manage any data generically. I pass in the value as a pointer reference which is then saved as a void pointer. Later when it is returned I do not know how to cast the void pointer back to the original value.
What do I need to do? Here is the sample struct.
typedef struct MyData {
int mNumber;
} MyData;
To simplify everything I have created a dummy function that simulates everything in a few lines of code.
void * give_and_go(void *data) {
void *tmp = data;
return tmp;
}
You can see it takes in a void pointer, sets it as a local variable and then returns it. Now I need to get the original value back.
MyData inVal;
inVal.mNumber = 100;
void * ptr = give_and_go(&inVal);
MyData outVal; // What converts ptr to the out value?
This is where I am stuck. I am using Xcode and it will not allow me to simply cast ptr to MyData or various alternatives that I have tried.
Any help is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该将 void 指针分配给 MyData 指针:
如果您使用的是 C++,则必须显式转换它,无论如何我都建议这样做,因为它适用于两种语言:
无论哪种情况,您都可以使用 < code>-> 运算符:
您也可以这样分配结构本身:
但这会复制结构,而其他形式让您指向原始结构(即分配给
outVal->mNumber
将更改inVal.mNumber
,反之亦然)。不存在任何一种先验偏好。这仅取决于您的意图。You should assign the void-pointer to a MyData-pointer:
If you are using C++, you will have to explicitly cast it, which I recommend anyway, since it works in both languages:
In either case, you can then deference using the
->
operator:You can also assign the struct itself thus:
But this copies the struct, whereas the other forms leave you pointing back to the original struct (i.e., assigning to
outVal->mNumber
will changeinVal.mNumber
, and vice-versa). There is no a priori preference one way or other. It just depends on what you intend.将 void* 投射回 MyData*,然后取消引用它。
MyData *outVal = (MyData*)(ptr);
Cast your void* back to a MyData*, then dereference it.
MyData *outVal = (MyData*)(ptr);
根据我所提供的代码,您正在尝试将 void 指针转换回非指针类型。这行不通。
相反,将 void 指针转换回正确类型的指针:
From what I can tell about the code you provided, you are trying to cast a void pointer back to a non-pointer type. This won't work.
Instead, cast your void pointer back to a pointer of the correct type: