在 Objective C 中调用 C 回调
Calling C callback in Objective C
这是我尝试在 C 函数回调中使用 Objective C 方法的代码。结果它崩溃了:
typedef void (^BlockCallback)(u_char *args, const struct pcap_pkthdr *header, const u_char *packet);
- (void)startProcessing:(BlockCallback)progressCallback
{
pcap_loop(handle, packetsNumber, (__bridge void *)progressCallback, NULL);// it crashes here
}
....
[self startProcessing:^(u_char *args, const struct pcap_pkthdr *header, const u_char *packet) {
/// some processing code here
}];
我不明白 C 怎么能那样调用块。这应该可以工作,前提是第一个指针 (user
) 是用户定义的 context,您可以使用它来将 self
传递给回调函数:
static void _pcapCallback(u_char *user, const struct pcap_pkthdr *header, const u_char *packet)
{
MyClass *myClass = (MyClass *)user;
[myClass _pcapHeader:header packet:packet];
}
@implementation MyClass
- (void)_pcapHeader:(const struct pcap_pkthdr *)header
packet:(const u_char *)packet
{
// do thing
}
- (void)startProcessing
{
pcap_loop(handle, packetsNumber, _pcapCallback, self);
}
...
@end
这是我尝试在 C 函数回调中使用 Objective C 方法的代码。结果它崩溃了:
typedef void (^BlockCallback)(u_char *args, const struct pcap_pkthdr *header, const u_char *packet);
- (void)startProcessing:(BlockCallback)progressCallback
{
pcap_loop(handle, packetsNumber, (__bridge void *)progressCallback, NULL);// it crashes here
}
....
[self startProcessing:^(u_char *args, const struct pcap_pkthdr *header, const u_char *packet) {
/// some processing code here
}];
我不明白 C 怎么能那样调用块。这应该可以工作,前提是第一个指针 (user
) 是用户定义的 context,您可以使用它来将 self
传递给回调函数:
static void _pcapCallback(u_char *user, const struct pcap_pkthdr *header, const u_char *packet)
{
MyClass *myClass = (MyClass *)user;
[myClass _pcapHeader:header packet:packet];
}
@implementation MyClass
- (void)_pcapHeader:(const struct pcap_pkthdr *)header
packet:(const u_char *)packet
{
// do thing
}
- (void)startProcessing
{
pcap_loop(handle, packetsNumber, _pcapCallback, self);
}
...
@end