c - 如何将参数传递给函数指针

标签 c pointers dereference call-by-value

我正在使用 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。

最佳答案

什么阻碍了你做

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

关于c - 如何将参数传递给函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53480557/

相关文章:

c - 金额计算失败

c - 用于基于 C 的远程控制/守护进程 (IPC/RPC) 的优雅 API?

c++ - C++中的平均指针位置

rust - 从 Option<Rc<RefCell<T>>> 解包并访问 T

C 指针和 var 作用域

c - 防止外部调用 lib 文件内的函数

c - 使用单个字符指针迭代二维数组

c++ - 复制构造函数指针对象

c - C 中 int *[5] 和 int (*)[5] 有什么区别?

C 中的 union 解引用和递减