【问题标题】:Dereference self in C function with ARC, reference passed as intptr_t使用 ARC 在 C 函数中取消引用 self,引用作为 intptr_t 传递
【发布时间】:2015-02-06 14:05:59
【问题描述】:

我有一些需要使用 C 函数的 Objective-C 代码。该函数的“UserData”类型为long。我需要使用它来传递对self 的引用,所以我像这样传递它:

Proc((intptr_t) self);

另一端的干净解决方案如下所示:

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

但这在 ARC 下是不允许的:“ARC 不允许将 'intptr_t' (aka 'long') 转换为 'MyType *'”

C 函数是在MyType 的实现中声明的,所以我不需要保留它。如何使用 ARC 在long 中获取我的参考信息?

【问题讨论】:

  • 为什么您认为将其转换为void** 是正确的?如果 self 只是一个指针,则将其转换为该指针类型。然后,更挑剔,uintptr_t 是无符号整数类型,long 是有符号类型。

标签: c++ objective-c c cocoa automatic-ref-counting


【解决方案1】:

从问题中不清楚你有什么或你尝试了什么,所以这里有一个简单的示例,它可以工作,也许你可以从中找出你的问题:

@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

【讨论】:

  • 太棒了,做到了!谢谢。
【解决方案2】:

您不会向我们展示所有内容,但通常如果 MyType*self 的类型,您应该这样做

Proc((intptr_t)self);

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

【讨论】:

  • 这就是我开始的地方,但后来我得到了这个错误:Cast of 'intptr_t' (aka 'long') to 'MyType *' is disallowed with ARC
  • 解决它的唯一方法是使用临时引用self 的全局变量,这很混乱并且可能导致线程问题。
猜你喜欢
  • 2013-07-18
  • 2016-09-10
  • 2015-09-16
  • 2013-11-30
  • 1970-01-01
  • 1970-01-01
  • 2012-12-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多