从我所做的阅读中,Core Audio在很大程度上依赖于回调(和C++,但这是另一个故事).
我理解设置一个函数的概念(类型),该函数由另一个函数重复调用以完成任务.我只是不明白他们是如何设置以及他们如何工作的.任何例子将不胜感激.
aib*_*aib 194
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);
...
}
Run Code Online (Sandbox Code Playgroud)
这里,populate_array
函数将函数指针作为其第三个参数,并调用它来获取用于填充数组的值.我们编写了回调getNextRandomValue
函数,它返回一个random-ish值,并将指针传递给它populate_array
.populate_array
将调用我们的回调函数10次,并将返回的值分配给给定数组中的元素.
小智 118
以下是C中回调的示例.
假设你想编写一些代码,允许在某些事件发生时注册回调.
首先定义用于回调的函数类型:
typedef void (*event_cb_t)(const struct event *evt, void *userdata);
Run Code Online (Sandbox Code Playgroud)
现在,定义一个用于注册回调的函数:
int event_cb_register(event_cb_t cb, void *userdata);
Run Code Online (Sandbox Code Playgroud)
这是注册回调的代码:
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);
...
Run Code Online (Sandbox Code Playgroud)
在事件调度程序的内部,回调可以存储在如下所示的结构中:
struct event_cb {
event_cb_t cb;
void *data;
};
Run Code Online (Sandbox Code Playgroud)
这就是执行回调的代码.
struct event_cb *callback;
...
/* Get the event_cb that you want to execute */
callback->cb(event, callback->data);
Run Code Online (Sandbox Code Playgroud)
Gau*_*aju 19
一个简单的回叫计划.希望它能回答你的问题.
#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;
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
函数调用PrintTwoNumbers中的函数(*numberSource)是一个从PrintTwoNumbers内部"回调"/执行的函数,由运行时的代码决定.
因此,如果你有类似pthread函数的东西,你可以指定另一个函数在其实例化的循环内运行.
C 中的回调是提供给另一个函数以在另一个函数执行其任务时的某个时间点“回调”的函数。
有两种使用回调的方式:同步回调和异步回调。同步回调被提供给另一个函数,该函数将执行一些任务,然后在任务完成后返回给调用者。异步回调被提供给另一个函数,该函数将启动一个任务,然后返回给调用者,任务可能未完成。
同步回调通常用于向另一个函数提供委托,另一个函数将任务的某个步骤委托给该函数。这种委托的典型例子是函数bsearch()
和qsort()
来自 C 标准库的函数。这两个函数都接受在函数提供的任务期间使用的回调,以便正在搜索的数据的类型(在 的情况下bsearch()
)或排序的数据(在 的情况下)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);
}
}
Run Code Online (Sandbox Code Playgroud)
异步回调的不同之处在于,当我们提供回调的被调用函数返回时,任务可能无法完成。这种类型的回调通常与异步 I/O 一起使用,其中启动 I/O 操作,然后在完成时调用回调。
在下面的程序中,我们创建一个套接字来侦听 TCP 连接请求,当收到请求时,进行侦听的函数会调用提供的回调函数。这个简单的应用程序可以通过在一个窗口中运行它来执行,同时使用该telnet
实用程序或 Web 浏览器尝试在另一个窗口中连接。
我从 Microsoftaccept()
在https://msdn.microsoft.com/en-us/library/windows/desktop/ms737526(v=vs.85).aspx提供的示例中提取了大部分 WinSock 代码
此应用程序listen()
使用端口 8282 在本地主机 127.0.0.1 上启动 a ,因此您可以使用telnet 127.0.0.1 8282
或http://127.0.0.1:8282/
。
此示例应用程序是作为带有 Visual Studio 2017 社区版的控制台应用程序创建的,它使用的是 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);
}
Run Code Online (Sandbox Code Playgroud)