Question

I'm using libssh2 and have a callback function defined outside my SSHWrapper object:

static void kbd_callback(const char *name, int name_len, const char *instruction, int instruction_len, int num_prompts, const LIBSSH2_USERAUTH_KBDINT_PROMPT *prompts, LIBSSH2_USERAUTH_KBDINT_RESPONSE *responses, void **abstract);

From within my SSHWrapper object I do the following, passing the callback function when authenticaing the session:

/* Create a session instance */
LIBSSH2_SESSION *session = libssh2_session_init_ex(NULL, NULL, NULL, self);
while ((rc = libssh2_userauth_keyboard_interactive(session, userChar, &kbd_callback)) == LIBSSH2_ERROR_EAGAIN);

What I'm wondering is, is it possible to move the kbd_callback() function inside my object, so that it's a class method: +(void) kbd_callback:...?

If so, how do I get the address of that function in order to pass it to the C function libssh2_userauth_keyboard_interactive()?

Was it helpful?

Solution

The approach you're taking now is reasonable. That said, Objective-C methods are in fact just C functions. The main thing complicating the approach you suggest is that they include two "hidden" arguments, self, and _cmd. self is the instance of the object the method is being called on, and _cmd is the selector for the method. You can't change these and their presence will make it impossible to make your function's arguments match those required for the callback function.

Just in case it's still interesting to you, you can get a function pointer to an Objective-C method like so:

IMP methodIMP = [self methodForSelector:@selector(someMethodThatTakesOneStringArgument:)];
void (*functionPointer)(id, SEL, NSString*) = (void (*)(id, SEL, NSString*))methodIMP;

// Then call it:
functionPointer(instance, @selector(someMethodThatTakesOneStringArgument:), aString);

EDIT: I posted a simple, complete program that demonstrates this code in action here: https://gist.github.com/2731937

OTHER TIPS

No. The underlying C function that gets created by + (void)method should not be called directly in this fashion. Unless you are very familiar with the underlying Objective-C runtime, messing with the IMP functions will only get you into trouble.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top