gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:25:11 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com