gpt4 book ai didi

C 查找哪个指针调用了函数

转载 作者:太空宇宙 更新时间:2023-11-04 01:12:28 25 4
gpt4 key购买 nike

场景:

有多个 C 结构,每个结构都包含指向同一函数的函数指针。如有必要,这些指针可以不同(指向指针的指针等),但最终都必须指向同一个函数。

问题:

当从其中一个指针调用函数时,我需要在函数内检索它是从哪个结构调用的。

例如

typedef struct A {
void * (*func)();
... /* Custom properties */
} * A;

typedef struct B {
void * (*func)();
... /* Custom properties */
} * B;


A a_init() {
A a;
... /* Custom initialisation, allocation, etc. */
a->func = myFunc;
return a;
}

B b_init() {
B b;
... /* Custom initialisation, allocation, etc. */
b->func = myFunc;
return b;
}


int main () {
A a = a_init();
void *something = a->func();
}


void * myFunc () {
// Need to get pointer to the instance of the struct this was called from here
}

有什么方法可以在 myFunc 中检索指向调用方的指针?如果有必要,我正在考虑创建指向函数指针等的指针,这样一个对象的每个实例都会有一个不同的指针,并将它们全部存储在一个中心位置以匹配它们,但这显然不会如果我什至找不到对象的实例或使用的指针,就可以工作。有什么想法吗?

编辑:

这个问题的意图比我提出的要广泛一些。 Currying 将是一个很好的解决方案,如果有人对如何在 C 中实现它有任何想法。我有一些想法,但我最终还是回到了这里。

最佳答案

我认为在该语言中没有任何方法可以做到这一点,除非明确地将一些标识符(作为参数或全局变量)传递给 myFunca_init() 的地址存在于调用堆栈中的某处,但程序无法访问它。

这就像如果有人突然出现在你家门口,你怎么能不问就知道那个人来自哪里?

关于C 查找哪个指针调用了函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9238155/

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