How to pass objective-c function as a callback to C function?

前端 未结 2 1668
你的背包
你的背包 2021-01-03 09:41

I want to call a c function from objective-c and pass objective-c function as a callback

the problem is this function has a callback as parameter, so I have to pass

2条回答
  •  时光说笑
    2021-01-03 09:58

    As matt already said, you cannot pass an Objective-C method as callback where a C function is expected. Objective-C methods are special functions, in particular the receiver ("self") is implicitly passed as first argument to the function.

    Therefore, to use an Objective-C method as request handler, you need an (intermediate) C function as handler and you have to pass self to that function, using the user_data argument. The C function can then call the Objective-C method:

    // This is the Objective-C request handler method:
    - (int)beginRequest:(struct mg_connection *)conn
    {
        // Your request handler ...
        return 1;
    }
    
    // This is the intermediate C function:
    static int begin_request_handler(struct mg_connection *conn) {
        const struct mg_request_info *request_info = mg_get_request_info(conn);
        // Cast the "user_data" back to an instance pointer of your class:
        YourClass *mySelf = (__bridge YourClass *)request_info->user_data;
        // Call instance method:
        return [mySelf beginRequest:conn];
    }
    
    - (IBAction)startserver:(id)sender
    {
        struct mg_callbacks callbacks;
        memset(&callbacks, 0, sizeof(callbacks));
        callbacks.begin_request = begin_request_handler;
        const char *options[] =
        {
            "document_root", "www",
            "listening_ports", "8080",
            NULL
        };
        // Pass "self" as "user_data" argument:
        mg_start(&callbacks, (__bridge void *)self, options);
    }
    

    Remarks:

    • If you don't use ARC (automatic reference counting) then you can omit the (__bridge ...) casts.
    • You must ensure that the instance of your class ("self") is not deallocated while the server is running. Otherwise the YourClass *mySelf would be invalid when the request handler is called.

提交回复
热议问题