Erphan Rajput
Erphan Rajput

Reputation: 21

passing function reference to a C pointer type, C will invoke the function

I have a simple question i.e. how can I pass objective-C function reference as a C function pointer so that C can invoke that function.

edit: Sorry for not providing the sample source here it is:

- (void)init {
      CLibStructure cLibObject;
      cLibObject.on_work_done = &cWorkDone;
}

the function that will point to on_work_done will have this signature in C

static void cWorkDone(const char *workInfo);

whereas in objective-C this is the signature that I made

- (void) workDoneWithStatusMessage:(const char *message);

Now i want is to point cLib.on_work_done the pointer to objective-c function, if I point to standard C function it works.

Upvotes: 0

Views: 536

Answers (2)

hauntsaninja
hauntsaninja

Reputation: 1019

You can create a function that calls the method, and then manipulate a pointer to that:

int function(NSObject *something, int someArg)
{
     return [something thisIsAMethod:someArg];
     //assuming NSObject has a method called thisIsAMethod that takes an int as a parameter and returns an int.
}

and then you could use a pointer to this function:

int (*pointerToFunction)(NSObject *, int) = &function;

Upvotes: 0

bbum
bbum

Reputation: 162722

In short, you can't. Not directly.

A method call is a combination of a target, the object to message, and the selector that identifies the method to call.

You need to bundle those up together somehow. With Blocks it is easy enough. With pure C APIs, it can typically be done with a context pointer or something like it.

Given that you posted no code, no examples, none of the API to be used, and none of the details about the C API itself, providing details is difficult.

Upvotes: 3

Related Questions