【问题标题】:How to pass arguments to function pointers如何将参数传递给函数指针
【发布时间】:2018-11-26 11:53:38
【问题描述】:

我正在使用 c 中的函数指针,因为我的自定义 API 库需要一个回调机制。 用一个简单的例子总结一下:

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

SY_msg 的大小为 1024 字节。 因此堆栈中有 1024 个字节。

指向 userfuncion() 的指针作为 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。

【问题讨论】:

  • 为什么不能简单地将分配留给调用者?
  • calback_wrapper[0] (*msg); /* 1204 are passed by value */ 你不能只传递msg 而不是*msg 并让函数期望一个指针而不是整个数据结构吗?据我了解,这是您自己的 API。你可以改变它。
  • 不,我不能,因为谁会释放()味精?
  • 内存管理必须对 userfunction() 不可见。
  • userfunction() 必须简单地按值接收 msg 结构,

标签: c pointers dereference call-by-value


【解决方案1】:

什么阻碍了你做事

// (...) 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;

【讨论】:

  • msg = 堆栈中的 1024 个字节
  • 用户函数 = 堆栈中的 1024 个字节
  • pmsg = 1024 字节在堆中
  • @Giorgio:您定义用户函数在堆栈上分配 1024 个字节:userfunction(SY_msg msg)。如果您不想要这个,请以不同的方式定义它。
  • 我正在寻找一种节省堆栈空间的聪明方法。最佳解决方案可能是 userfunction() 的堆中 1024 字节和堆栈中的 1024 字节。
【解决方案2】:

我的问题中有错误的假设。 用户 function() 的参数是在函数调用之后的堆栈中分配的。 也许某种“contextswich”可以解决这个问题。 示例:

  • 调用userfunction();
  • “上下文”
  • 释放堆
  • “上下文”
  • 恢复 userfunction();

但无论如何,都需要汇编代码 sn-ps。

【讨论】:

    猜你喜欢
    • 2012-11-26
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 2012-04-15
    • 2018-08-25
    相关资源
    最近更新 更多