0

I've already read several articles about this question, but none of them solve my problem.

Briefly, in my NSApplicationDelegate, I called a function pcap_loop, pcap_loop needs a function pointer as callback, the callback signature is

void got_packet(u_char *, const struct pcap_pkthdr *, const u_char *)

I want to pass one of the NSApplicationDelegate's method as callback, so I can use these data in my app, somebody suggest me using "SEL + IMP", but I can't pass the self to callback, also somebody suggest "block", not work.

So, any idea?

Thanks!

3
  • Why do you need to use an Objective-C method for this? If it needs a C function, pass it a C function, period. You won't be able to do anything else in the lack of a self pointer. Commented Nov 19, 2012 at 8:15
  • @H2CO3 Is there anyway for me to get the NSApplicationDelegate instance in callback? I mean, something like [NSApplicationDelegate sharedInstance] Commented Nov 19, 2012 at 8:35
  • 2
    @MartinLuo In Cocoa : [[NSApplication sharedApplication] delegate], or [NSApp delegate]. And in iOS [[UIApplication sharedApplication] delegate] Commented Nov 19, 2012 at 10:09

1 Answer 1

2

The essence of what you require can be found in this answer.

In your case you are calling pcap_loop:

int pcap_loop(pcap_t *p, int cnt, pcap_handler callback, u_char *user) 

where pcap_handler is:

void got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet); 

Now the last argument to pcap_loop, user, is passed as the first argument to got_packet, args and can be anything you wish. This corresponds to the argument cb_arg/anon in the previous answer. Now just follow the previous answer, passing a block which invokes your NSApplicationDelegate method as user and the C function to invoke that block as callback.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.