gpt4 book ai didi

C 钩子(Hook)/回调系统

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

我一直在努力弄清楚如何在 C 中实现 Hook 系统。谁能给我一些指示或示例?

最佳答案

使用函数指针:

struct callbacks {
void (*somethingHappened)(void *context);
bool (*shouldIDoSomething)(void *context);
};

void doSomethingAwesome(void *operationData, struct callbacks callbacks)
{
// context is the data you pass to the function
if (callbacks.shouldIDoSomething(context))
{
// do something
callbacks.somethingHappened(context);
}
}

或者,您可以创建一个调度服务:

struct dictionary
{
char **keys;
void **values;

int count;
};

struct list
{
void **values;

int count;
};

// functions to add, remove, etc;

struct dictionary *callbacks = NULL;
void registerForDispatch(char *key, void (*callback)(void *))
{
if (!callbacks)
{
callbacks = dictionary_create(10); // dictionary with 10 key / value pairs
}

if (!dictionary_containsKey(callbacks, key))
{
struct list *callBacksForKey = list_create(10); // default 10 callbacks, array should be auto-expanding

dictionary_setValue(callbacks, key, arr);
}

struct list *callBacksForKey = dictionary_getValue(callbacks, key);

list_addObject(callBacksForKey, callback);
}

void unregisterFromDispatch(char *key, void (*callback)(void *))
{
struct list *callBacksForKey = dictionary_getValue(callbacks, key);

list_removeObject(callback);
}

void sendNotification(char *key, void *context)
{
struct list *callBacksForKey = dictionary_getValue(callbacks, key);

for (int i = 0; list->count; i++)
{
void (*callback)(void *) = list->values[i];
callback(context);
}
}

使用第二种解决方案,您可以获得单个回调的多个监听器的优势。

关于C 钩子(Hook)/回调系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9547801/

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