我使用c中的函数指针,因为我需要为我的自定义API库提供回调机制。以一个简单的例子总结:
*userfunction*(SY_msg msg)
{
/* do something */
};
SY_msg的大小为1024字节。因此在堆栈中有1024个字节。
指向userfunction((的指针作为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
但我想要以下内容:
// (...) 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
有可能找到"某处"地址吗?我的编译器是gcc。
什么阻止你进行
// (...) 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
在上面的例子中,你可以替换
memcpy(&msg, pmsg, sizeof(SY_msg));
通过
msg = *pmsg;
我的问题中有错误的假设。user function((的参数是在函数调用之后在堆栈中分配的。也许某种"情境思维"可以解决这个问题。示例:
- 调用userfunction((
- "contextswich">
- 释放堆
- "contextswich">
- 恢复用户功能((
但在任何情况下,都会请求程序集代码段。