I was wondering about the use of the dpvt pointer in a subroutine that the aSub record uses when it is processed. My understanding is that the dpvt pointer is used for device support, but I was wondering if it can also be used as an alternative to static variables.
For instance, suppose I have a very simple asub record called count$(N) and I have two instances of it called count1 and count2. I want to keep track of the number of times that each of them have been processed. If my subroutine code is the following:
static long count_static(aSubRecord *prec)
{
long status = 0;
static int count = 1;
printf("I have been called %d time(s)\n", count);
count++;
return status;
}
epicsRegisterFunction(count_static);
I have been called 1 time(s)
I have been called 2 time(s)
I have been called 3 time(s)
I have been called 4 time(s)
I have been called 5 time(s)
This is wrong, because count2 was only called once.
s
tatic long count(aSubRecord *prec)
{
long status = 0;
if (!prec->dpvt)
{
prec->dpvt = (int *) calloc(1, sizeof(int));
}
if (prec->dpvt)
{
*((double *) prec->dpvt) += 1;
printf("I have been called %d time(s)\n", *((int *) prec->dpvt));
}
else
{
status = -1;
}
return status;
}
epicsRegisterFunction(count);
I have been called 1 time(s)
I have been called 2 time(s)
I have been called 3 time(s)
I have been called 4 time(s)
I have been called 1 time(s)
which is correct, since I only
processed count2 once.
Is it okay to use dpvt pointer
for "static" variable-like behavior or should a different methodology be used since dpvt pointer seems to be meant for device support.
An additional related question:
Suppose for device support, dpvt pointer points to a struct, which has a special free function associated with it (the struct might contain member variables that are dynamically allocated). Where can that be called so that there is no memory leaks from the
IOC?
Thanks,
Andy