在 Objective-C 中实现 C 回调
Implement C Callback in Objective-C
我正在使用用 C 编写的 SDK (Linphone),我需要将 C 文件中声明的调用状态更改处理函数实现到 objective-C 或最好在 Swift 环境中。
这是C中的声明:
// declaration
void call_state_changed(LinphoneCore *lc, LinphoneCall *call, LinphoneCallState cstate, const char *msg);
// typedef
typedef void (*LinphoneCoreCallStateChangedCb)(LinphoneCore *lc, LinphoneCall *call, LinphoneCallState cstate, const char *message);
这里是包含 属性 的结构,用于实现
所需的 LinphoneCoreCallStateChangedCb
typedef struct _LinphoneCoreVTable{
LinphoneCoreCallStateChangedCb call_state_changed;/**<Notifies call state changes*/
} LinphoneCoreVTable;
这是我的尝试:
_vTable->call_state_changed = ^(LinphoneCore *lc, LinphoneCall *call, LinphoneCallState cstate, const char *message)
{
}
错误如下:
正确的语法是什么?
谢谢!
您正在尝试使用 块,而您所需要的只是一个(可能 static
)C 函数,如下所示:
static void _linphoneCallback(LinphoneCore *lc, LinphoneCall *call,
LinphoneCallState cstate, const char *message)
{
// do thing
}
...
_vTable->call_state_changed = _linphoneCallback;
但是我看不出您如何将 Objective-C class 实例传递给回调,这使得回调难以在任何语言中使用,包括 C。
像这样定义回调
typedef void (^LinphoneCoreCallStateChangedCb)(LinphoneCore *lc, LinphoneCall *call, LinphoneCallState cstate, const char *message);
并使用它:
LinphoneCoreCallStateChangedCb callback = ^(LinphoneCore *lc, LinphoneCall *call, LinphoneCallState cstate, const char *message){};
我正在使用用 C 编写的 SDK (Linphone),我需要将 C 文件中声明的调用状态更改处理函数实现到 objective-C 或最好在 Swift 环境中。
这是C中的声明:
// declaration
void call_state_changed(LinphoneCore *lc, LinphoneCall *call, LinphoneCallState cstate, const char *msg);
// typedef
typedef void (*LinphoneCoreCallStateChangedCb)(LinphoneCore *lc, LinphoneCall *call, LinphoneCallState cstate, const char *message);
这里是包含 属性 的结构,用于实现
所需的 LinphoneCoreCallStateChangedCbtypedef struct _LinphoneCoreVTable{
LinphoneCoreCallStateChangedCb call_state_changed;/**<Notifies call state changes*/
} LinphoneCoreVTable;
这是我的尝试:
_vTable->call_state_changed = ^(LinphoneCore *lc, LinphoneCall *call, LinphoneCallState cstate, const char *message)
{
}
错误如下:
正确的语法是什么?
谢谢!
您正在尝试使用 块,而您所需要的只是一个(可能 static
)C 函数,如下所示:
static void _linphoneCallback(LinphoneCore *lc, LinphoneCall *call,
LinphoneCallState cstate, const char *message)
{
// do thing
}
...
_vTable->call_state_changed = _linphoneCallback;
但是我看不出您如何将 Objective-C class 实例传递给回调,这使得回调难以在任何语言中使用,包括 C。
像这样定义回调
typedef void (^LinphoneCoreCallStateChangedCb)(LinphoneCore *lc, LinphoneCall *call, LinphoneCallState cstate, const char *message);
并使用它:
LinphoneCoreCallStateChangedCb callback = ^(LinphoneCore *lc, LinphoneCall *call, LinphoneCallState cstate, const char *message){};