C中可能的回调默认值?

问题描述 投票:0回答:1

我有问题,代码胜于文字。


static void message_cb(int friend_number, char const *message) {
    // ...

    // I need to access instance (from `init`) here.

    // I can't modify the parameters of message_cb unfortunately...


    // ...
} 

// There will be a lots of different `instance`,
// so I can't really use a global variable...
static void init(Chat *instance)
{
    // ...

    callback_message(message_cb);

    // ...
}

简而言之,我需要执行以下操作,但在C中:(例如根据instance参数生成函数)

static void init(Chat *instance)
{
    // ...

    callback_message(void (int friend_number, char const *message) {
        // Here I can access `instance`
    });

    // ...
}

对不起,我的英语简短而又可能很糟糕,这不是我的母语...

提前感谢

c callback
1个回答
0
投票

鉴于您不能修改消息的参数 cb 不幸的是使用可设置的值初始化回调的一种方法是创建extern范围内的变量,也许在.h文件中提供对需要其当前值或地址的任何.c文件的可见性(取决于instance的定义方式):

。h文件

//declare project global here
extern <type><name>;

file1.c

//define project global here
<type><name> = somevalue;

回应关于线程的评论...

如果要在多线程环境中使用对象(消息,值,其他对象),则需要对其进行保护,以控制何时可以通过创建它们来修改其值,例如在以下两种方式之一:

  • 使用锁结构(例如互斥锁)以使用关键部分]保护共享变量。
  • 使用原子操作访问对象,新的C标准,C11支持此构造。
  • [关于此主题有很多教程,例如this one

这是通过使用锁来使用线程安全性的概念的快速而肮脏的示例:

// Your function modified with pseudo code for concept illustration

//static void init(Chat *instance)
static bool init(Chat *instance)
{
    bool status = FALSE;
    struct ts_lock lock = {0};
    get_lock(&lock);

    if(lock.granted)
    {
        //populate message from instance here
        // <some code to populate 'message'>
        callback_message(void (int friend_number, char const *message) {
        // Here I can access `instance`

        status = TRUE;
        release_lock(lock);
    }

    return status;

    // ...
}
© www.soinside.com 2019 - 2024. All rights reserved.