Reputation: 546
I am trying to retrieve value from void* array
passed to function as argument.
This is what is passed to my function as void * data
argument:
void *sredp[3];
sredp[0] = (void*)buf;
sredp[1] = (void*)(&len);
sredp[2] = (void*)(&ri);
source: https://github.com/kamailio/kamailio/blob/master/udp_server.c#L481
For the dereferencing of first two fields I am using this code:
int my_fnc(void *data)
{
str *obuf;
obuf = (str*)data;
}
str
is internal type of Kamailio server (http://www.asipto.com/pub/kamailio-devel-guide/#c05str).
I am wondering how can I dereference ri
field from void *data
. I am trying to do this like this:
int my_fnc(void *data)
{
struct receive_info * ri;
ri = (struct receive_info*)(data + 2*sizeof(void*));
}
And when I am trying to print receive_info
structure (https://github.com/sipwise/kamailio/blob/4ee1c6a799713b999aac23de74b26badbe06d0aa/ip_addr.h#L132) it seems to giving me some data but I have no idea if theese are just some random bytes from memory or it is correct data that I should retrieve.
So my question is if I am doing it right and if there is another/better way to reach my goal?
Upvotes: 0
Views: 2050
Reputation: 206577
data
in my_fnc
has to be treated as void**
to be able to extract the real data.
int my_fnc(void *data)
{
void** sredp = (void**)data;
str* obuf = (str*)srdep[0];
// The pointer that contains len can be obtained from srdep[1]
// The pointer that contains ri can be obtained from srdep[2]
}
Here's a simple program that illustrates that:
#include <stdio.h>
void foo(void* data)
{
void** realData = (void**)data;
void* p1 = realData[0];
void* p2 = realData[1];
void* p3 = realData[2];
printf("sredp[0]: %p\n", p1);
printf("sredp[1]: %p\n", p2);
printf("sredp[2]: %p\n", p3);
int a1 = *(int*)p1;
float a2 = *(float*)p2;
double a3 = *(double*)p3;
printf("a1: %d\n", a1);
printf("a2: %f\n", a2);
printf("a3: %lf\n", a3);
}
int main()
{
int a1 = 10;
float a2 = 20.0f;
double a3 = 40.0;
void *sredp[3];
sredp[0] = &a1;
sredp[1] = &a2;
sredp[2] = &a3;
printf("sredp[0]: %p\n", sredp[0]);
printf("sredp[1]: %p\n", sredp[1]);
printf("sredp[2]: %p\n", sredp[2]);
foo(sredp);
}
Sample output from running the program:
sredp[0]: 0x28ac2c sredp[1]: 0x28ac28 sredp[2]: 0x28ac20 sredp[0]: 0x28ac2c sredp[1]: 0x28ac28 sredp[2]: 0x28ac20 a1: 10 a2: 20.000000 a3: 40.000000
Upvotes: 1
Reputation: 56452
You can't do pointer arithmetic with void* in C. It would require it to use sizeof(void), which doesn't really exists.
The problem is in your function signature :
int my_fnc(void *data)
Your pointer is not a void*, it's a void**. So cast it before using it :
void** d = (void**) data;
ri = (struct receive_info*)(d + 2);
This will use a sizeof(void*), which is a standard pointer size.
Upvotes: 1