How to pass arguments to function pointers

97 Views Asked by At

I'm working with function pointers in c because I need a callback mechanism for my custom API library. Summarizing with a simple example:

*userfunction*(SY_msg msg)
{
  /* do something */
};

The size of SY_msg is 1024 bytes. 1024 bytes are therefore in the stack.

A pointer to userfuncion() is present as first element in calback_wrapper[].

here is an example of use:
// (...) some code
    SY_msg* msg;
    msg = SYmalloc (sizeof(SY_msg)); /* it takes 1024 bytes in heap */
// (...) some code
    calback_wrapper[0] (*msg); /*  1204 are passed by value  */
    /* during userfunction() execution , 1024 unused bytes are present in the heap */
    free (msg); /* now finally heap is free */
// (...) some code

But I would like to have the following:

// (...) some code
    SY_msg* msg;
    msg = SYmalloc (sizeof(SY_msg)); /* it takes 1024 bytes in heap */
// (...) some code
    memcpy(someplace,msg,sizeof(SY_msg); /*  where "someplace" is a point in the stack referred by the argument of userfunction()  */
    free (msg); /*  heap is free */
    calback_wrapper[0] (*someplace); /* is starts userfunction() execution */
// (...) some code

It is possible to find "someplace" address? My compiler is gcc.

2

There are 2 best solutions below

9
On

What keeps from you doing

// (...) some code
SY_msg msg, * pmsg;
pmsg = SYmalloc (sizeof(SY_msg)); /* it takes 1024 bytes in heap */
// (...) some code using pmsg instead of msg
memcpy(&msg, pmsg, sizeof(SY_msg)); /*  where "someplace" is a point in the stack referred by the argument of userfunction()  */
free (pmsg); /*  heap is free */
calback_wrapper[0] (msg); /* is starts userfunction() execution */
// (...) some code

in the above example you can replace

memcpy(&msg, pmsg, sizeof(SY_msg));

by

msg = *pmsg;
0
On

There are wrong assumptions in my question. The argument of user function() is allocated in the stack just AFTER the function call. Maybe some kind of "contextswich" could solve this problem. Example:

  • Call userfunction();
  • "contextswich"
  • Free the heap
  • "contextswich"
  • Resume userfunction();

But in any case, an assembly code snippets is requested.