从我所做的阅读中,Core Audio在很大程度上依赖于回调(和C ++,但这是另一个故事)。

我理解设置一个由另一个函数重复调用以完成任务的函数的概念(类型)。我只是不明白他们是如何设置以及他们如何工作的。任何例子都将不胜感激。

有帮助吗?

解决方案

没有“回调”在C中 - 不超过任何其他通用编程概念。

它们是使用函数指针实现的。这是一个例子:

void populate_array(int *array, size_t arraySize, int (*getNextValue)(void))
{
    for (size_t i=0; i<arraySize; i++)
        array[i] = getNextValue();
}

int getNextRandomValue(void)
{
    return rand();
}

int main(void)
{
    int myarray[10];
    populate_array(myarray, 10, getNextRandomValue);
    ...
}

这里, populate_array 函数将一个函数指针作为其第三个参数,并调用它来获取用于填充数组的值。我们编写了回调 getNextRandomValue ,它返回一个random-ish值,并将指针传递给 populate_array populate_array 将调用我们的回调函数10次,并将返回的值分配给给定数组中的元素。

其他提示

以下是C语言中回调的示例。

假设您想要编写一些代码,允许在发生某些事件时调用回调函数。

首先定义用于回调的函数类型:

typedef void (*event_cb_t)(const struct event *evt, void *userdata);

现在,定义一个用于注册回调的函数:

int event_cb_register(event_cb_t cb, void *userdata);

这是注册回调的代码:

static void my_event_cb(const struct event *evt, void *data)
{
    /* do stuff and things with the event */
}

...
   event_cb_register(my_event_cb, &my_custom_data);
...

在事件调度程序的内部,回调可能存储在一个如下所示的结构中:

struct event_cb {
    event_cb_t cb;
    void *data;
};

这就是执行回调的代码。

struct event_cb *callback;

...

/* Get the event_cb that you want to execute */

callback->cb(event, callback->data);

一个简单的回叫计划。希望它能回答你的问题。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include "../../common_typedef.h"

typedef void (*call_back) (S32, S32);

void test_call_back(S32 a, S32 b)
{
    printf("In call back function, a:%d \t b:%d \n", a, b);
}

void call_callback_func(call_back back)
{
    S32 a = 5;
    S32 b = 7;

    back(a, b);
}

S32 main(S32 argc, S8 *argv[])
{
    S32 ret = SUCCESS;

    call_back back;

    back = test_call_back;

    call_callback_func(back);

    return ret;
}

C中的回调函数等同于指定在另一个函数中使用的函数参数/变量。 Wiki示例

在下面的代码中,

#include <stdio.h>
#include <stdlib.h>

/* The calling function takes a single callback as a parameter. */
void PrintTwoNumbers(int (*numberSource)(void)) {
    printf("%d and %d\n", numberSource(), numberSource());
}

/* A possible callback */
int overNineThousand(void) {
    return (rand() % 1000) + 9001;
}

/* Another possible callback. */
int meaningOfLife(void) {
    return 42;
}

/* Here we call PrintTwoNumbers() with three different callbacks. */
int main(void) {
    PrintTwoNumbers(&rand);
    PrintTwoNumbers(&overNineThousand);
    PrintTwoNumbers(&meaningOfLife);
    return 0;
}

函数调用PrintTwoNumbers中的函数(* numberSource)是一个“回调”函数。 /从PrintTwoNumbers内部执行,如运行时的代码所示。

因此,如果您有类似pthread函数的东西,您可以指定另一个函数在其实例化的循环内运行。

C中的回调通常使用函数指针和关联的数据指针来实现。您将函数 on_event()和数据指针传递给框架函数 watch_events()(例如)。当事件发生时,将使用您的数据和一些特定于事件的数据调用您的函数。

回调也用于GUI编程。 GTK +教程信号和回调理论

这个维基百科文章在C中有一个例子。

一个很好的例子是,为扩充Apache Web服务器而编写的新模块通过传递它们的函数指针来注册主apache进程,以便回调这些函数来处理网页请求。

C中的回调是提供给另一个功能以“回叫”的功能。在其他功能正在执行任务的某个时刻。

使用回调的两种方式:同步回调和异步打回来。向另一个将执行某项任务的函数提供同步回调,然后在任务完成时返回给调用者。异步回调被提供给另一个函数,该函数将启动一个任务,然后返回调用者,任务可能没有完成。

同步回调通常用于向另一个函数提供委托,另一个函数委托该任务的某个步骤。此委派的典型示例是C标准库中的函数 bsearch() qsort()。这两个函数都采用在函数提供的任务期间使用的回调,以便在 bsearch()的情况下搜索的数据的类型,或者在<的情况下进行排序。 code> qsort(),不需要被正在使用的函数所知。

例如,这是一个使用不同比较函数,同步回调的 bsearch()的小示例程序。通过允许我们将数据比较委托给回调函数, bsearch()函数允许我们在运行时决定我们想要使用哪种比较。这是同步的,因为当 bsearch()函数返回时,任务完成。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    int iValue;
    int kValue;
    char label[6];
} MyData;

int cmpMyData_iValue (MyData *item1, MyData *item2)
{
    if (item1->iValue < item2->iValue) return -1;
    if (item1->iValue > item2->iValue) return 1;
    return 0;
}

int cmpMyData_kValue (MyData *item1, MyData *item2)
{
    if (item1->kValue < item2->kValue) return -1;
    if (item1->kValue > item2->kValue) return 1;
    return 0;
}

int cmpMyData_label (MyData *item1, MyData *item2)
{
    return strcmp (item1->label, item2->label);
}

void bsearch_results (MyData *srch, MyData *found)
{
        if (found) {
            printf ("found - iValue = %d, kValue = %d, label = %s\n", found->iValue, found->kValue, found->label);
        } else {
            printf ("item not found, iValue = %d, kValue = %d, label = %s\n", srch->iValue, srch->kValue, srch->label);
        }
}

int main ()
{
    MyData dataList[256] = {0};

    {
        int i;
        for (i = 0; i < 20; i++) {
            dataList[i].iValue = i + 100;
            dataList[i].kValue = i + 1000;
            sprintf (dataList[i].label, "%2.2d", i + 10);
        }
    }

//  ... some code then we do a search
    {
        MyData srchItem = { 105, 1018, "13"};
        MyData *foundItem = bsearch (&srchItem, dataList, 20, sizeof(MyData), cmpMyData_iValue );

        bsearch_results (&srchItem, foundItem);

        foundItem = bsearch (&srchItem, dataList, 20, sizeof(MyData), cmpMyData_kValue );
        bsearch_results (&srchItem, foundItem);

        foundItem = bsearch (&srchItem, dataList, 20, sizeof(MyData), cmpMyData_label );
        bsearch_results (&srchItem, foundItem);
    }
}

异步回调的不同之处在于,当我们提供回调的被调用函数返回时,该任务可能无法完成。这种类型的回调通常用于启动I / O操作的异步I / O,然后在完成时调用回调。

在下面的程序中,我们创建一个套接字来监听TCP连接请求,当收到请求时,执行监听的函数会调用提供的回调函数。这个简单的应用程序可以通过在一个窗口中运行它来执行,同时使用 telnet 实用程序或Web浏览器尝试在另一个窗口中连接。

我通过 accept()函数解除了Microsoft提供的示例中的大部分WinSock代码。 windows / desktop / ms737526(v = vs.85).aspx“rel =”nofollow noreferrer“> https://msdn.microsoft.com/en-us/library/windows/desktop/ms737526(v = vs.85)的.aspx

此应用程序使用端口8282在本地主机127.0.0.1上启动 listen(),因此您可以使用 telnet 127.0.0.1 8282 http://127.0.0.1:8282/

此示例应用程序是使用Visual Studio 2017 Community Edition创建的控制台应用程序,它使用的是Microsoft WinSock版本的套接字。对于Linux应用程序,WinSock函数需要替换为Linux替代品,Windows线程库将使用 pthreads

#include <stdio.h>
#include <winsock2.h>
#include <stdlib.h>
#include <string.h>

#include <Windows.h>

// Need to link with Ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")

// function for the thread we are going to start up with _beginthreadex().
// this function/thread will create a listen server waiting for a TCP
// connection request to come into the designated port.
// _stdcall modifier required by _beginthreadex().
int _stdcall ioThread(void (*pOutput)())
{
    //----------------------
    // Initialize Winsock.
    WSADATA wsaData;
    int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != NO_ERROR) {
        printf("WSAStartup failed with error: %ld\n", iResult);
        return 1;
    }
    //----------------------
    // Create a SOCKET for listening for
    // incoming connection requests.
    SOCKET ListenSocket;
    ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ListenSocket == INVALID_SOCKET) {
        wprintf(L"socket failed with error: %ld\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }
    //----------------------
    // The sockaddr_in structure specifies the address family,
    // IP address, and port for the socket that is being bound.
    struct sockaddr_in service;
    service.sin_family = AF_INET;
    service.sin_addr.s_addr = inet_addr("127.0.0.1");
    service.sin_port = htons(8282);

    if (bind(ListenSocket, (SOCKADDR *)& service, sizeof(service)) == SOCKET_ERROR) {
        printf("bind failed with error: %ld\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }
    //----------------------
    // Listen for incoming connection requests.
    // on the created socket
    if (listen(ListenSocket, 1) == SOCKET_ERROR) {
        printf("listen failed with error: %ld\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }
    //----------------------
    // Create a SOCKET for accepting incoming requests.
    SOCKET AcceptSocket;
    printf("Waiting for client to connect...\n");

    //----------------------
    // Accept the connection.
    AcceptSocket = accept(ListenSocket, NULL, NULL);
    if (AcceptSocket == INVALID_SOCKET) {
        printf("accept failed with error: %ld\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }
    else
        pOutput ();   // we have a connection request so do the callback

    // No longer need server socket
    closesocket(ListenSocket);

    WSACleanup();
    return 0;
}

// our callback which is invoked whenever a connection is made.
void printOut(void)
{
    printf("connection received.\n");
}

#include <process.h>

int main()
{
     // start up our listen server and provide a callback
    _beginthreadex(NULL, 0, ioThread, printOut, 0, NULL);
    // do other things while waiting for a connection. In this case
    // just sleep for a while.
    Sleep(30000);
}

通常这可以通过使用函数指针来完成,函数指针是指向函数的内存位置的特殊变量。然后,您可以使用它来使用特定参数调用该函数。所以可能会有一个设置回调函数的函数。这将接受一个函数指针,然后将该地址存储在可以使用它的地方。之后,当触发指定的事件时,它将调用该函数。

通过示例理解一个想法要容易得多。 到目前为止,有关C中回调函数的内容是很好的答案,但使用该功能的最大好处可能是保持代码干净整洁。

实施例

以下C代码实现了快速排序。 下面代码中最有趣的一行是这一行,我们可以在其中看到回调函数:

qsort(arr,N,sizeof(int),compare_s2b);

compare_s2b是qsort()用来调用函数的函数名。这使qsort()保持整洁(因此更容易维护)。你只需从另一个函数内部通过名称调用一个函数(当然,函数原型声明,至少必须先从另一个函数调用它之前)。

完整代码

#include <stdio.h>
#include <stdlib.h>

int arr[]={56,90,45,1234,12,3,7,18};
//function prototype declaration 

int compare_s2b(const void *a,const void *b);

int compare_b2s(const void *a,const void *b);

//arranges the array number from the smallest to the biggest
int compare_s2b(const void* a, const void* b)
{
    const int* p=(const int*)a;
    const int* q=(const int*)b;

    return *p-*q;
}

//arranges the array number from the biggest to the smallest
int compare_b2s(const void* a, const void* b)
{
    const int* p=(const int*)a;
    const int* q=(const int*)b;

    return *q-*p;
}

int main()
{
    printf("Before sorting\n\n");

    int N=sizeof(arr)/sizeof(int);

    for(int i=0;i<N;i++)
    {
        printf("%d\t",arr[i]);
    }

    printf("\n");

    qsort(arr,N,sizeof(int),compare_s2b);

    printf("\nSorted small to big\n\n");

    for(int j=0;j<N;j++)
    {
        printf("%d\t",arr[j]);
    }

    qsort(arr,N,sizeof(int),compare_b2s);

    printf("\nSorted big to small\n\n");

    for(int j=0;j<N;j++)
    {
        printf("%d\t",arr[j]);
    }

    exit(0);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top