Ravi
Ravi

Reputation: 41

Typecasting structure pointer to character pointer

I have structure defined as

typedef struct Check
{     
    char conn_type;  
    int fd;
 }Check;
 Check *msg;
 //malloc code not writing.Consider it as malloced.
 msg->con_type = 1;
 msg->fd = listen_fd = 10;
add_select_msg_com_con((char*)msg);

I saw somewhere in code , they were typecasting it as (char *)Check

eg -

add_select((char*)msg)

In its definnation

void add_select(char* data_ptr)
{
    struct epoll_event pfd
    pfd.data.ptr = (void *) data_ptr;
 }

I want to know , where ptr in pfd.data.ptr is void pointer how it will get value of ptr as connection type. How it works? Thanks

Upvotes: 1

Views: 1495

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

Ok let's define a structure properly (yours is anonymous but I assume it is a typo):

typedef struct 
{     
    char conn_type;  
    int fd;
 } Check;

now in the sender's code I define & initialize a variable of type Check called msg.

Check msg = {'a',12};

I want to send an event with the contents of msg, using a library that does not know Check. I create a pointer on char and take reference of msg

char *pmsg = (char*)&msg;

Then I call

add_select(pmsg);

They cast as char * so it fits the prototype of add_select (it doesn't change the value of the pointer, but it's type so the compiler accepts it)

In add_select it is cast again as void * (which is unnecessary since void * is the generic pointer type) which is the generic pointer to pass user-data in messages within a framework that is not aware of your Check structure (the epoll_event structure has a "user data" void * pointer used to pass any information to the event listener)

I would rather define add_select like this:

void add_select(void* data_ptr)
{
    struct epoll_event pfd;
    pfd.data.ptr = data_ptr;
 }

So I can call it directly with the msg variable, no need to cast:

add_select(&msg);

now on the message reception side

The program (event listener) that gets the message (on the other end of the transmission) has to know that the anonymous byte-stream message hides a Check structure to perform the reverse cast:

// convert/map the anonymous data to a `Check` structure
Check *recieved_msg = (Check *)pfd.data.ptr;

so it can access recieved_msg->conn_type etc...

Upvotes: 3

Related Questions