开发者

How is a void pointer dereferenced back to the original struct in C?

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 ret开发者_如何学运维urns 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.


You should assign the void-pointer to a MyData-pointer:

MyData *outVal = ptr;

If you are using C++, you will have to explicitly cast it, which I recommend anyway, since it works in both languages:

MyData *outVal = (MyData *)ptr;

In either case, you can then deference using the -> operator:

outVal->mNumber

You can also assign the struct itself thus:

MyData outVal = *(MyData *)ptr;

But this copies the struct, whereas the other forms leave you pointing back to the original struct (i.e., assigning to outVal->mNumber will change inVal.mNumber, and vice-versa). There is no a priori preference one way or other. It just depends on what you intend.


Cast your void* back to a MyData*, then dereference it.

MyData *outVal = (MyData*)(ptr);


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:

MyData inVal;
inVal.mNumber = 100;
void* ptr = give_and_go(& inVal);
MyData* outVal = (MyData*)ptr;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜