简体   繁体   中英

Dereference self in C function with ARC, reference passed as intptr_t

I've got some Objective-C code that needs to work with a C function. The "UserData" of the function is of type long . I need to use that to pass a reference to self , so I pass it like so:

Proc((intptr_t) self);

The clean solution on the other end would look like this:

int Proc(long UserData) {
    MyType *refToSelf = (MyType*)(intptr_t)UserData;
}

But that's not allowed under ARC: "Cast of 'intptr_t' (aka 'long') to 'MyType *' is disallowed with ARC"

The C function is declared inside of MyType 's implementation, so I have no need to retain it. How can I get my reference in and out of a long with ARC?

It is not clear from the question what you have or what you've tried, so here is a trivial sample which works and maybe you can figure out your issue from it:

@interface Basic : NSObject

- (void) identify;

@end

@implementation Basic

- (void) identify
{
   NSLog(@"Basic instance: %p", self);
}

@end

@implementation AppDelegate

void cFunction(long UserData)
{
   Basic *bp = (__bridge Basic *)(void *)UserData; // cast to void * then bridge without
                                                   // transferring ownership to the ARC world 
   [bp identify];
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
   NSAssert(sizeof(long) == sizeof(void *), @"can't work, sizes don't match");

   Basic *b = [Basic new];
   cFunction((long)(__bridge void *)b); // bridge to the C world without retaining
                                        // or transferring ownership then cast as long
   [b identify];
}

@end

HTH

You don't show us everything, but normally if MyType* is the type of self you should just do

Proc((intptr_t)self);

and

MyType *refToSelf = (MyType*)(intptr_t)UserData;

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