简体   繁体   中英

Accessing a class ivar from a C function

I have a C function in a class (yes, has to be in C) and I need to access an ivar from that class. The ivar in question is a NSMutableDictionary.

From what I understand, C functions don't have direct access to ivars of a class and a reference must be passed to them. So, I have added this before the implementation

static NSMutableDictionary *myIvarRef;

and did this on the init of that class.

- (id)init
{
    self = [super init];
    if (self != nil)
    {
        myIvar = [[NSMutableDictionary alloc] init];
        myIvarRef = myIvar;
    }
    return self;
}

later, inside that function, when I try to use myIvarRef it is nil.

What am I missing?

thanks


The C function is complex to put here, but the line that I am trying to use is like this

MyObject obj = myIvarRef[myKey];

I put a breakpoint at this line and when it stops I type po myIvarRef on console and it gives me nil.

Your code has the big problem that the static myIvarRef variable is overwritten in each init call, and therefore always points to the ivar of the last created object.

A better solution would be to pass the object pointer as an additional argument to the C function. Something like this:

void myFunction(void *uData, /* other parameters */ )
{
    MyClass *obj = (__bridge MyClass *)(uData);
    // Now you can access all properties, ivars etc of obj.   
    // ...
}

- (void)myMethod
{
    // Call C function from Objective-C method:
    myFunction((__bridge void *)(self), /* other arguments */ );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM