Archived

This topic is now archived and is closed to further replies.

klubbkid

Function Pointers....

Recommended Posts

I know how to setup a function pointer in C.... My question is that when you make the function pointer you have to specify which parameters will be passed in....is there any way I can make this dynamic? So I could maybe do something like this: void Blah(char *parseMe) { // parse the string...but how? } FunctionPointer = Blah FunctionPointer("%d %d", variableOne, variableTwo); Without having to specify that the function pointer will need two integers passed in?

Share this post


Link to post
Share on other sites
i think the only way to do that would be to declare a variable arg function and ptr,


void MyFunc(...)
{
//do your func here
//using the va_start, va_end
}

void FuncPtr*(...); //syntax correct? i always have to look.


FuncPtr = MyFunc;
FuncPtr( arg1, arg2, arg3 );



but that may have significant overhead.
good luck

crazy166
some people think i''m crazy, some people know i am

Share this post


Link to post
Share on other sites
doh! i see where you''re going.

yes, use variable arguments like so:



void MyFunc( char* string, ... )
{
}



and your code will work. unsure of parsing, though. look up va_start, va_end, va_list in some C or C++ reference.

Share this post


Link to post
Share on other sites
Another idea is to make your function pointer point to a function that takes a single void* parameter, which could then be used to pass the address of a structure containing any number of parameters.

For example:

  

// function pointer

typedef void(*FuncPtr)(void*);

// function which takes one input and gives one output

void Double(void* parms)
{
typedef struct{int in,out;}Parms;

Parms* p = (Parms*)parms;

p->out = (p->in*2);
}

// function which takes two input2 and gives one output

void Add(void* parms)
{
typedef struct{int in1,in2,out;}Parms;

Parms* p = (Parms*)parms;

p->out = p->in1 + p->in2;
}

int main()
{
int result;
FuncPtr fp;

{
typedef struct{int in,out;}Parms;

Parms parms = {10,0};

fp = Double;
fp(&parms);

result = parms.out;
}

{
typedef struct{int in1,in2,out;}Parms;

Parms parms = {10,20,0};

fp = Add;
fp(&parms);

result = parms.out;
}

return 0;
}



Whilst this may not be the best way to go about your problem, it is a solution.

Andy.

Share this post


Link to post
Share on other sites