b1onic
b1onic

Reputation: 239

How to get the current instance of an object from a C function

I implemented a C callback in the implementation of an object which is used by a function from a private framework, so I have no control on the arguments passed to the callback. I would like to use self from the callback. Thanks.

EDIT:

MyObject.h/.m

#import "PrivateFramework.h"
@interface MyObject : NSObject    

-(void) start;  

@end  

void callback(void* arg1, int arg2);  
void callback(void* arg1, int arg2) {  

 /* 
   here I would like to use self (current instance of the object) but
    I can't pass a pointer to the instance in the callback since I don't
    control what is passed to it.
 */



@implementation MyObject

-(void)start {  

    // this function is inside a private framework.
    PrivateFunction(&callback);  
 }
@end

Upvotes: 0

Views: 340

Answers (2)

user1509623
user1509623

Reputation: 192

The concept of a callback is what blocks were created for. I would look into the Block Programming Guide. It's not a C-style callback, but it has a similar use.

Upvotes: 0

Wain
Wain

Reputation: 119031

Couple of options:

  1. Use a singleton to manage the process
  2. Add a 'class' variable (file level static) to hold the requesting instance

    static MyObject *callbackResponder = nil;

This would probably go between your #imports and @implementation in the .m file.

Upvotes: 1

Related Questions